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 uint64_t          JvmtiExport::_redefinition_count                        = 0;
 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_pop_frame                             = false;
1204 bool              JvmtiExport::_can_force_early_return                    = false;
1205 bool              JvmtiExport::_can_get_owned_monitor_info                = false;
1206 
1207 bool              JvmtiExport::_early_vmstart_recorded                    = false;
1208 
1209 bool              JvmtiExport::_should_post_single_step                   = false;
1210 bool              JvmtiExport::_should_post_field_access                  = false;
1211 bool              JvmtiExport::_should_post_field_modification            = false;
1212 bool              JvmtiExport::_should_post_class_load                    = false;
1213 bool              JvmtiExport::_should_post_class_prepare                 = false;
1214 bool              JvmtiExport::_should_post_class_unload                  = false;
1215 bool              JvmtiExport::_should_post_thread_life                   = false;
1216 bool              JvmtiExport::_should_clean_up_heap_objects              = false;
1217 bool              JvmtiExport::_should_post_native_method_bind            = false;
1218 bool              JvmtiExport::_should_post_dynamic_code_generated        = false;
1219 bool              JvmtiExport::_should_post_data_dump                     = false;
1220 bool              JvmtiExport::_should_post_compiled_method_load          = false;
1221 bool              JvmtiExport::_should_post_compiled_method_unload        = false;
1222 bool              JvmtiExport::_should_post_monitor_contended_enter       = false;
1223 bool              JvmtiExport::_should_post_monitor_contended_entered     = false;
1224 bool              JvmtiExport::_should_post_monitor_wait                  = false;
1225 bool              JvmtiExport::_should_post_monitor_waited                = false;
1226 bool              JvmtiExport::_should_post_garbage_collection_start      = false;
1227 bool              JvmtiExport::_should_post_garbage_collection_finish     = false;
1228 bool              JvmtiExport::_should_post_object_free                   = false;
1229 bool              JvmtiExport::_should_post_resource_exhausted            = false;
1230 bool              JvmtiExport::_should_post_vm_object_alloc               = false;
1231 bool              JvmtiExport::_should_post_sampled_object_alloc          = false;
1232 bool              JvmtiExport::_should_post_on_exceptions                 = false;
1233 
1234 ////////////////////////////////////////////////////////////////////////////////////////////////
1235 
1236 
1237 //
1238 // JVMTI single step management
1239 //
1240 void JvmtiExport::at_single_stepping_point(JavaThread *thread, Method* method, address location) {
1241   assert(JvmtiExport::should_post_single_step(), "must be single stepping");
1242 
1243   HandleMark hm(thread);
1244   methodHandle mh(thread, method);
1245 
1246   // update information about current location and post a step event
1247   JvmtiThreadState *state = thread->jvmti_thread_state();
1248   if (state == NULL) {
1249     return;
1250   }
1251   EVT_TRIG_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Trg Single Step triggered",
1252                       JvmtiTrace::safe_get_thread_name(thread)));
1253   if (!state->hide_single_stepping()) {
1254     if (state->is_pending_step_for_popframe()) {
1255       state->process_pending_step_for_popframe();
1256     }
1257     if (state->is_pending_step_for_earlyret()) {
1258       state->process_pending_step_for_earlyret();
1259     }
1260     JvmtiExport::post_single_step(thread, mh(), location);
1261   }
1262 }
1263 
1264 
1265 void JvmtiExport::expose_single_stepping(JavaThread *thread) {
1266   JvmtiThreadState *state = thread->jvmti_thread_state();
1267   if (state != NULL) {
1268     state->clear_hide_single_stepping();
1269   }
1270 }
1271 
1272 
1273 bool JvmtiExport::hide_single_stepping(JavaThread *thread) {
1274   JvmtiThreadState *state = thread->jvmti_thread_state();
1275   if (state != NULL && state->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1276     state->set_hide_single_stepping();
1277     return true;
1278   } else {
1279     return false;
1280   }
1281 }
1282 
1283 void JvmtiExport::post_class_load(JavaThread *thread, Klass* klass) {
1284   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1285     return;
1286   }
1287   HandleMark hm(thread);
1288 
1289   EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Trg Class Load triggered",
1290                       JvmtiTrace::safe_get_thread_name(thread)));
1291   JvmtiThreadState* state = thread->jvmti_thread_state();
1292   if (state == NULL) {
1293     return;
1294   }
1295   JvmtiEnvThreadStateIterator it(state);
1296   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1297     if (ets->is_enabled(JVMTI_EVENT_CLASS_LOAD)) {
1298       JvmtiEnv *env = ets->get_env();
1299       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1300         continue;
1301       }
1302       EVT_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Evt Class Load sent %s",
1303                                          JvmtiTrace::safe_get_thread_name(thread),
1304                                          klass==NULL? "NULL" : klass->external_name() ));
1305       JvmtiClassEventMark jem(thread, klass);
1306       JvmtiJavaThreadEventTransition jet(thread);
1307       jvmtiEventClassLoad callback = env->callbacks()->ClassLoad;
1308       if (callback != NULL) {
1309         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1310       }
1311     }
1312   }
1313 }
1314 
1315 
1316 void JvmtiExport::post_class_prepare(JavaThread *thread, Klass* klass) {
1317   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1318     return;
1319   }
1320   HandleMark hm(thread);
1321 
1322   EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Trg Class Prepare triggered",
1323                       JvmtiTrace::safe_get_thread_name(thread)));
1324   JvmtiThreadState* state = thread->jvmti_thread_state();
1325   if (state == NULL) {
1326     return;
1327   }
1328   JvmtiEnvThreadStateIterator it(state);
1329   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1330     if (ets->is_enabled(JVMTI_EVENT_CLASS_PREPARE)) {
1331       JvmtiEnv *env = ets->get_env();
1332       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1333         continue;
1334       }
1335       EVT_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Evt Class Prepare sent %s",
1336                                             JvmtiTrace::safe_get_thread_name(thread),
1337                                             klass==NULL? "NULL" : klass->external_name() ));
1338       JvmtiClassEventMark jem(thread, klass);
1339       JvmtiJavaThreadEventTransition jet(thread);
1340       jvmtiEventClassPrepare callback = env->callbacks()->ClassPrepare;
1341       if (callback != NULL) {
1342         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1343       }
1344     }
1345   }
1346 }
1347 
1348 void JvmtiExport::post_class_unload(Klass* klass) {
1349   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1350     return;
1351   }
1352 
1353   // postings to the service thread so that it can perform them in a safe
1354   // context and in-order.
1355   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
1356   ResourceMark rm;
1357   // JvmtiDeferredEvent copies the string.
1358   JvmtiDeferredEvent event = JvmtiDeferredEvent::class_unload_event(klass->name()->as_C_string());
1359   JvmtiDeferredEventQueue::enqueue(event);
1360 }
1361 
1362 
1363 void JvmtiExport::post_class_unload_internal(const char* name) {
1364   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1365     return;
1366   }
1367   assert(Thread::current()->is_Java_thread(), "must be called from ServiceThread");
1368   JavaThread *thread = JavaThread::current();
1369   HandleMark hm(thread);
1370 
1371   EVT_TRIG_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Trg Class Unload triggered" ));
1372   if (JvmtiEventController::is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1373 
1374     JvmtiEnvIterator it;
1375     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1376       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1377         continue;
1378       }
1379       if (env->is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1380         EVT_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Evt Class Unload sent %s", name));
1381 
1382         JvmtiEventMark jem(thread);
1383         JvmtiJavaThreadEventTransition jet(thread);
1384         jvmtiExtensionEvent callback = env->ext_callbacks()->ClassUnload;
1385         if (callback != NULL) {
1386           (*callback)(env->jvmti_external(), jem.jni_env(), name);
1387         }
1388       }
1389     }
1390   }
1391 }
1392 
1393 
1394 void JvmtiExport::post_thread_start(JavaThread *thread) {
1395   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1396     return;
1397   }
1398   assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
1399 
1400   EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Trg Thread Start event triggered",
1401                       JvmtiTrace::safe_get_thread_name(thread)));
1402 
1403   // do JVMTI thread initialization (if needed)
1404   JvmtiEventController::thread_started(thread);
1405 
1406   // Do not post thread start event for hidden java thread.
1407   if (JvmtiEventController::is_enabled(JVMTI_EVENT_THREAD_START) &&
1408       !thread->is_hidden_from_external_view()) {
1409     JvmtiEnvIterator it;
1410     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1411       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1412         continue;
1413       }
1414       if (env->is_enabled(JVMTI_EVENT_THREAD_START)) {
1415         EVT_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Evt Thread Start event sent",
1416                      JvmtiTrace::safe_get_thread_name(thread) ));
1417 
1418         JvmtiThreadEventMark jem(thread);
1419         JvmtiJavaThreadEventTransition jet(thread);
1420         jvmtiEventThreadStart callback = env->callbacks()->ThreadStart;
1421         if (callback != NULL) {
1422           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1423         }
1424       }
1425     }
1426   }
1427 }
1428 
1429 
1430 void JvmtiExport::post_thread_end(JavaThread *thread) {
1431   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1432     return;
1433   }
1434   EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Trg Thread End event triggered",
1435                       JvmtiTrace::safe_get_thread_name(thread)));
1436 
1437   JvmtiThreadState *state = thread->jvmti_thread_state();
1438   if (state == NULL) {
1439     return;
1440   }
1441 
1442   // Do not post thread end event for hidden java thread.
1443   if (state->is_enabled(JVMTI_EVENT_THREAD_END) &&
1444       !thread->is_hidden_from_external_view()) {
1445 
1446     JvmtiEnvThreadStateIterator it(state);
1447     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1448       if (ets->is_enabled(JVMTI_EVENT_THREAD_END)) {
1449         JvmtiEnv *env = ets->get_env();
1450         if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1451           continue;
1452         }
1453         EVT_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Evt Thread End event sent",
1454                      JvmtiTrace::safe_get_thread_name(thread) ));
1455 
1456         JvmtiThreadEventMark jem(thread);
1457         JvmtiJavaThreadEventTransition jet(thread);
1458         jvmtiEventThreadEnd callback = env->callbacks()->ThreadEnd;
1459         if (callback != NULL) {
1460           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1461         }
1462       }
1463     }
1464   }
1465 }
1466 
1467 void JvmtiExport::post_object_free(JvmtiEnv* env, jlong tag) {
1468   assert(SafepointSynchronize::is_at_safepoint(), "must be executed at safepoint");
1469   assert(env->is_enabled(JVMTI_EVENT_OBJECT_FREE), "checking");
1470 
1471   EVT_TRIG_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Trg Object Free triggered" ));
1472   EVT_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Evt Object Free sent"));
1473 
1474   jvmtiEventObjectFree callback = env->callbacks()->ObjectFree;
1475   if (callback != NULL) {
1476     (*callback)(env->jvmti_external(), tag);
1477   }
1478 }
1479 
1480 void JvmtiExport::post_resource_exhausted(jint resource_exhausted_flags, const char* description) {
1481 
1482   JavaThread *thread  = JavaThread::current();
1483 
1484   // JDK-8213834: handlers of ResourceExhausted may attempt some analysis
1485   // which often requires running java.
1486   // This will cause problems on threads not able to run java, e.g. compiler
1487   // threads. To forestall these problems, we therefore suppress sending this
1488   // event from threads which are not able to run java.
1489   if (!thread->can_call_java()) {
1490     return;
1491   }
1492 
1493   EVT_TRIG_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Trg resource exhausted event triggered" ));
1494 
1495   JvmtiEnvIterator it;
1496   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1497     if (env->is_enabled(JVMTI_EVENT_RESOURCE_EXHAUSTED)) {
1498       EVT_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Evt resource exhausted event sent" ));
1499 
1500       JvmtiThreadEventMark jem(thread);
1501       JvmtiJavaThreadEventTransition jet(thread);
1502       jvmtiEventResourceExhausted callback = env->callbacks()->ResourceExhausted;
1503       if (callback != NULL) {
1504         (*callback)(env->jvmti_external(), jem.jni_env(),
1505                     resource_exhausted_flags, NULL, description);
1506       }
1507     }
1508   }
1509 }
1510 
1511 void JvmtiExport::post_method_entry(JavaThread *thread, Method* method, frame current_frame) {
1512   HandleMark hm(thread);
1513   methodHandle mh(thread, method);
1514 
1515   EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Trg Method Entry triggered %s.%s",
1516                      JvmtiTrace::safe_get_thread_name(thread),
1517                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1518                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1519 
1520   JvmtiThreadState* state = thread->jvmti_thread_state();
1521   if (state == NULL || !state->is_interp_only_mode()) {
1522     // for any thread that actually wants method entry, interp_only_mode is set
1523     return;
1524   }
1525 
1526   state->incr_cur_stack_depth();
1527 
1528   if (state->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1529     JvmtiEnvThreadStateIterator it(state);
1530     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1531       if (ets->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1532         EVT_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Evt Method Entry sent %s.%s",
1533                                              JvmtiTrace::safe_get_thread_name(thread),
1534                                              (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1535                                              (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1536 
1537         JvmtiEnv *env = ets->get_env();
1538         JvmtiMethodEventMark jem(thread, mh);
1539         JvmtiJavaThreadEventTransition jet(thread);
1540         jvmtiEventMethodEntry callback = env->callbacks()->MethodEntry;
1541         if (callback != NULL) {
1542           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_methodID());
1543         }
1544       }
1545     }
1546   }
1547 }
1548 
1549 void JvmtiExport::post_method_exit(JavaThread *thread, Method* method, frame current_frame) {
1550   HandleMark hm(thread);
1551   methodHandle mh(thread, method);
1552 
1553   EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Trg Method Exit triggered %s.%s",
1554                      JvmtiTrace::safe_get_thread_name(thread),
1555                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1556                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1557 
1558   JvmtiThreadState *state = thread->jvmti_thread_state();
1559   if (state == NULL || !state->is_interp_only_mode()) {
1560     // for any thread that actually wants method exit, interp_only_mode is set
1561     return;
1562   }
1563 
1564   // return a flag when a method terminates by throwing an exception
1565   // i.e. if an exception is thrown and it's not caught by the current method
1566   bool exception_exit = state->is_exception_detected() && !state->is_exception_caught();
1567 
1568 
1569   if (state->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1570     Handle result;
1571     jvalue value;
1572     value.j = 0L;
1573 
1574     // if the method hasn't been popped because of an exception then we populate
1575     // the return_value parameter for the callback. At this point we only have
1576     // the address of a "raw result" and we just call into the interpreter to
1577     // convert this into a jvalue.
1578     if (!exception_exit) {
1579       oop oop_result;
1580       BasicType type = current_frame.interpreter_frame_result(&oop_result, &value);
1581       if (is_reference_type(type)) {
1582         result = Handle(thread, oop_result);
1583       }
1584     }
1585 
1586     JvmtiEnvThreadStateIterator it(state);
1587     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1588       if (ets->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1589         EVT_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Evt Method Exit sent %s.%s",
1590                                             JvmtiTrace::safe_get_thread_name(thread),
1591                                             (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1592                                             (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1593 
1594         JvmtiEnv *env = ets->get_env();
1595         JvmtiMethodEventMark jem(thread, mh);
1596         if (result.not_null()) {
1597           value.l = JNIHandles::make_local(thread, result());
1598         }
1599         JvmtiJavaThreadEventTransition jet(thread);
1600         jvmtiEventMethodExit callback = env->callbacks()->MethodExit;
1601         if (callback != NULL) {
1602           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1603                       jem.jni_methodID(), exception_exit,  value);
1604         }
1605       }
1606     }
1607   }
1608 
1609   JvmtiEnvThreadStateIterator it(state);
1610   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1611     if (ets->has_frame_pops()) {
1612       int cur_frame_number = state->cur_stack_depth();
1613 
1614       if (ets->is_frame_pop(cur_frame_number)) {
1615         // we have a NotifyFramePop entry for this frame.
1616         // now check that this env/thread wants this event
1617         if (ets->is_enabled(JVMTI_EVENT_FRAME_POP)) {
1618           EVT_TRACE(JVMTI_EVENT_FRAME_POP, ("[%s] Evt Frame Pop sent %s.%s",
1619                                             JvmtiTrace::safe_get_thread_name(thread),
1620                                             (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1621                                             (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1622 
1623           // we also need to issue a frame pop event for this frame
1624           JvmtiEnv *env = ets->get_env();
1625           JvmtiMethodEventMark jem(thread, mh);
1626           JvmtiJavaThreadEventTransition jet(thread);
1627           jvmtiEventFramePop callback = env->callbacks()->FramePop;
1628           if (callback != NULL) {
1629             (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1630                         jem.jni_methodID(), exception_exit);
1631           }
1632         }
1633         // remove the frame's entry
1634         ets->clear_frame_pop(cur_frame_number);
1635       }
1636     }
1637   }
1638 
1639   state->decr_cur_stack_depth();
1640 }
1641 
1642 
1643 // Todo: inline this for optimization
1644 void JvmtiExport::post_single_step(JavaThread *thread, Method* method, address location) {
1645   HandleMark hm(thread);
1646   methodHandle mh(thread, method);
1647 
1648   JvmtiThreadState *state = thread->jvmti_thread_state();
1649   if (state == NULL) {
1650     return;
1651   }
1652   JvmtiEnvThreadStateIterator it(state);
1653   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1654     ets->compare_and_set_current_location(mh(), location, JVMTI_EVENT_SINGLE_STEP);
1655     if (!ets->single_stepping_posted() && ets->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1656       EVT_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Evt Single Step sent %s.%s @ " INTX_FORMAT,
1657                     JvmtiTrace::safe_get_thread_name(thread),
1658                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1659                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1660                     location - mh()->code_base() ));
1661 
1662       JvmtiEnv *env = ets->get_env();
1663       JvmtiLocationEventMark jem(thread, mh, location);
1664       JvmtiJavaThreadEventTransition jet(thread);
1665       jvmtiEventSingleStep callback = env->callbacks()->SingleStep;
1666       if (callback != NULL) {
1667         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1668                     jem.jni_methodID(), jem.location());
1669       }
1670 
1671       ets->set_single_stepping_posted();
1672     }
1673   }
1674 }
1675 
1676 void JvmtiExport::post_exception_throw(JavaThread *thread, Method* method, address location, oop exception) {
1677   HandleMark hm(thread);
1678   methodHandle mh(thread, method);
1679   Handle exception_handle(thread, exception);
1680 
1681   JvmtiThreadState *state = thread->jvmti_thread_state();
1682   if (state == NULL) {
1683     return;
1684   }
1685 
1686   EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION, ("[%s] Trg Exception thrown triggered",
1687                       JvmtiTrace::safe_get_thread_name(thread)));
1688   if (!state->is_exception_detected()) {
1689     state->set_exception_detected();
1690     JvmtiEnvThreadStateIterator it(state);
1691     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1692       if (ets->is_enabled(JVMTI_EVENT_EXCEPTION) && (exception != NULL)) {
1693 
1694         EVT_TRACE(JVMTI_EVENT_EXCEPTION,
1695                      ("[%s] Evt Exception thrown sent %s.%s @ " INTX_FORMAT,
1696                       JvmtiTrace::safe_get_thread_name(thread),
1697                       (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1698                       (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1699                       location - mh()->code_base() ));
1700 
1701         JvmtiEnv *env = ets->get_env();
1702         JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1703 
1704         // It's okay to clear these exceptions here because we duplicate
1705         // this lookup in InterpreterRuntime::exception_handler_for_exception.
1706         EXCEPTION_MARK;
1707 
1708         bool should_repeat;
1709         vframeStream st(thread);
1710         assert(!st.at_end(), "cannot be at end");
1711         Method* current_method = NULL;
1712         // A GC may occur during the Method::fast_exception_handler_bci_for()
1713         // call below if it needs to load the constraint class. Using a
1714         // methodHandle to keep the 'current_method' from being deallocated
1715         // if GC happens.
1716         methodHandle current_mh = methodHandle(thread, current_method);
1717         int current_bci = -1;
1718         do {
1719           current_method = st.method();
1720           current_mh = methodHandle(thread, current_method);
1721           current_bci = st.bci();
1722           do {
1723             should_repeat = false;
1724             Klass* eh_klass = exception_handle()->klass();
1725             current_bci = Method::fast_exception_handler_bci_for(
1726               current_mh, eh_klass, current_bci, THREAD);
1727             if (HAS_PENDING_EXCEPTION) {
1728               exception_handle = Handle(thread, PENDING_EXCEPTION);
1729               CLEAR_PENDING_EXCEPTION;
1730               should_repeat = true;
1731             }
1732           } while (should_repeat && (current_bci != -1));
1733           st.next();
1734         } while ((current_bci < 0) && (!st.at_end()));
1735 
1736         jmethodID catch_jmethodID;
1737         if (current_bci < 0) {
1738           catch_jmethodID = 0;
1739           current_bci = 0;
1740         } else {
1741           catch_jmethodID = jem.to_jmethodID(current_mh);
1742         }
1743 
1744         JvmtiJavaThreadEventTransition jet(thread);
1745         jvmtiEventException callback = env->callbacks()->Exception;
1746         if (callback != NULL) {
1747           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1748                       jem.jni_methodID(), jem.location(),
1749                       jem.exception(),
1750                       catch_jmethodID, current_bci);
1751         }
1752       }
1753     }
1754   }
1755 
1756   // frames may get popped because of this throw, be safe - invalidate cached depth
1757   state->invalidate_cur_stack_depth();
1758 }
1759 
1760 
1761 void JvmtiExport::notice_unwind_due_to_exception(JavaThread *thread, Method* method, address location, oop exception, bool in_handler_frame) {
1762   HandleMark hm(thread);
1763   methodHandle mh(thread, method);
1764   Handle exception_handle(thread, exception);
1765 
1766   JvmtiThreadState *state = thread->jvmti_thread_state();
1767   if (state == NULL) {
1768     return;
1769   }
1770   EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1771                     ("[%s] Trg unwind_due_to_exception triggered %s.%s @ %s" INTX_FORMAT " - %s",
1772                      JvmtiTrace::safe_get_thread_name(thread),
1773                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1774                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1775                      location==0? "no location:" : "",
1776                      location==0? 0 : location - mh()->code_base(),
1777                      in_handler_frame? "in handler frame" : "not handler frame" ));
1778 
1779   if (state->is_exception_detected()) {
1780 
1781     state->invalidate_cur_stack_depth();
1782     if (!in_handler_frame) {
1783       // Not in exception handler.
1784       if(state->is_interp_only_mode()) {
1785         // method exit and frame pop events are posted only in interp mode.
1786         // When these events are enabled code should be in running in interp mode.
1787         JvmtiExport::post_method_exit(thread, method, thread->last_frame());
1788         // The cached cur_stack_depth might have changed from the
1789         // operations of frame pop or method exit. We are not 100% sure
1790         // the cached cur_stack_depth is still valid depth so invalidate
1791         // it.
1792         state->invalidate_cur_stack_depth();
1793       }
1794     } else {
1795       // In exception handler frame. Report exception catch.
1796       assert(location != NULL, "must be a known location");
1797       // Update cur_stack_depth - the frames above the current frame
1798       // have been unwound due to this exception:
1799       assert(!state->is_exception_caught(), "exception must not be caught yet.");
1800       state->set_exception_caught();
1801 
1802       JvmtiEnvThreadStateIterator it(state);
1803       for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1804         if (ets->is_enabled(JVMTI_EVENT_EXCEPTION_CATCH) && (exception_handle() != NULL)) {
1805           EVT_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1806                      ("[%s] Evt ExceptionCatch sent %s.%s @ " INTX_FORMAT,
1807                       JvmtiTrace::safe_get_thread_name(thread),
1808                       (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1809                       (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1810                       location - mh()->code_base() ));
1811 
1812           JvmtiEnv *env = ets->get_env();
1813           JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1814           JvmtiJavaThreadEventTransition jet(thread);
1815           jvmtiEventExceptionCatch callback = env->callbacks()->ExceptionCatch;
1816           if (callback != NULL) {
1817             (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1818                       jem.jni_methodID(), jem.location(),
1819                       jem.exception());
1820           }
1821         }
1822       }
1823     }
1824   }
1825 }
1826 
1827 oop JvmtiExport::jni_GetField_probe(JavaThread *thread, jobject jobj, oop obj,
1828                                     Klass* klass, jfieldID fieldID, bool is_static) {
1829   if (*((int *)get_field_access_count_addr()) > 0 && thread->has_last_Java_frame()) {
1830     // At least one field access watch is set so we have more work
1831     // to do. This wrapper is used by entry points that allow us
1832     // to create handles in post_field_access_by_jni().
1833     post_field_access_by_jni(thread, obj, klass, fieldID, is_static);
1834     // event posting can block so refetch oop if we were passed a jobj
1835     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1836   }
1837   return obj;
1838 }
1839 
1840 oop JvmtiExport::jni_GetField_probe_nh(JavaThread *thread, jobject jobj, oop obj,
1841                                        Klass* klass, jfieldID fieldID, bool is_static) {
1842   if (*((int *)get_field_access_count_addr()) > 0 && thread->has_last_Java_frame()) {
1843     // At least one field access watch is set so we have more work
1844     // to do. This wrapper is used by "quick" entry points that don't
1845     // allow us to create handles in post_field_access_by_jni(). We
1846     // override that with a ResetNoHandleMark.
1847     ResetNoHandleMark rnhm;
1848     post_field_access_by_jni(thread, obj, klass, fieldID, is_static);
1849     // event posting can block so refetch oop if we were passed a jobj
1850     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1851   }
1852   return obj;
1853 }
1854 
1855 void JvmtiExport::post_field_access_by_jni(JavaThread *thread, oop obj,
1856                                            Klass* klass, jfieldID fieldID, bool is_static) {
1857   // We must be called with a Java context in order to provide reasonable
1858   // values for the klazz, method, and location fields. The callers of this
1859   // function don't make the call unless there is a Java context.
1860   assert(thread->has_last_Java_frame(), "must be called with a Java context");
1861 
1862   ResourceMark rm;
1863   fieldDescriptor fd;
1864   // if get_field_descriptor finds fieldID to be invalid, then we just bail
1865   bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1866   assert(valid_fieldID == true,"post_field_access_by_jni called with invalid fieldID");
1867   if (!valid_fieldID) return;
1868   // field accesses are not watched so bail
1869   if (!fd.is_field_access_watched()) return;
1870 
1871   HandleMark hm(thread);
1872   Handle h_obj;
1873   if (!is_static) {
1874     // non-static field accessors have an object, but we need a handle
1875     assert(obj != NULL, "non-static needs an object");
1876     h_obj = Handle(thread, obj);
1877   }
1878   post_field_access(thread,
1879                     thread->last_frame().interpreter_frame_method(),
1880                     thread->last_frame().interpreter_frame_bcp(),
1881                     klass, h_obj, fieldID);
1882 }
1883 
1884 void JvmtiExport::post_field_access(JavaThread *thread, Method* method,
1885   address location, Klass* field_klass, Handle object, jfieldID field) {
1886 
1887   HandleMark hm(thread);
1888   methodHandle mh(thread, method);
1889 
1890   JvmtiThreadState *state = thread->jvmti_thread_state();
1891   if (state == NULL) {
1892     return;
1893   }
1894   EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Trg Field Access event triggered",
1895                       JvmtiTrace::safe_get_thread_name(thread)));
1896   JvmtiEnvThreadStateIterator it(state);
1897   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1898     if (ets->is_enabled(JVMTI_EVENT_FIELD_ACCESS)) {
1899       EVT_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Evt Field Access event sent %s.%s @ " INTX_FORMAT,
1900                      JvmtiTrace::safe_get_thread_name(thread),
1901                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1902                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1903                      location - mh()->code_base() ));
1904 
1905       JvmtiEnv *env = ets->get_env();
1906       JvmtiLocationEventMark jem(thread, mh, location);
1907       jclass field_jclass = jem.to_jclass(field_klass);
1908       jobject field_jobject = jem.to_jobject(object());
1909       JvmtiJavaThreadEventTransition jet(thread);
1910       jvmtiEventFieldAccess callback = env->callbacks()->FieldAccess;
1911       if (callback != NULL) {
1912         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1913                     jem.jni_methodID(), jem.location(),
1914                     field_jclass, field_jobject, field);
1915       }
1916     }
1917   }
1918 }
1919 
1920 oop JvmtiExport::jni_SetField_probe(JavaThread *thread, jobject jobj, oop obj,
1921                                     Klass* klass, jfieldID fieldID, bool is_static,
1922                                     char sig_type, jvalue *value) {
1923   if (*((int *)get_field_modification_count_addr()) > 0 && thread->has_last_Java_frame()) {
1924     // At least one field modification watch is set so we have more work
1925     // to do. This wrapper is used by entry points that allow us
1926     // to create handles in post_field_modification_by_jni().
1927     post_field_modification_by_jni(thread, obj, klass, fieldID, is_static, sig_type, value);
1928     // event posting can block so refetch oop if we were passed a jobj
1929     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1930   }
1931   return obj;
1932 }
1933 
1934 oop JvmtiExport::jni_SetField_probe_nh(JavaThread *thread, jobject jobj, oop obj,
1935                                        Klass* klass, jfieldID fieldID, bool is_static,
1936                                        char sig_type, jvalue *value) {
1937   if (*((int *)get_field_modification_count_addr()) > 0 && thread->has_last_Java_frame()) {
1938     // At least one field modification watch is set so we have more work
1939     // to do. This wrapper is used by "quick" entry points that don't
1940     // allow us to create handles in post_field_modification_by_jni(). We
1941     // override that with a ResetNoHandleMark.
1942     ResetNoHandleMark rnhm;
1943     post_field_modification_by_jni(thread, obj, klass, fieldID, is_static, sig_type, value);
1944     // event posting can block so refetch oop if we were passed a jobj
1945     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1946   }
1947   return obj;
1948 }
1949 
1950 void JvmtiExport::post_field_modification_by_jni(JavaThread *thread, oop obj,
1951                                                  Klass* klass, jfieldID fieldID, bool is_static,
1952                                                  char sig_type, jvalue *value) {
1953   // We must be called with a Java context in order to provide reasonable
1954   // values for the klazz, method, and location fields. The callers of this
1955   // function don't make the call unless there is a Java context.
1956   assert(thread->has_last_Java_frame(), "must be called with Java context");
1957 
1958   ResourceMark rm;
1959   fieldDescriptor fd;
1960   // if get_field_descriptor finds fieldID to be invalid, then we just bail
1961   bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1962   assert(valid_fieldID == true,"post_field_modification_by_jni called with invalid fieldID");
1963   if (!valid_fieldID) return;
1964   // field modifications are not watched so bail
1965   if (!fd.is_field_modification_watched()) return;
1966 
1967   HandleMark hm(thread);
1968 
1969   Handle h_obj;
1970   if (!is_static) {
1971     // non-static field accessors have an object, but we need a handle
1972     assert(obj != NULL, "non-static needs an object");
1973     h_obj = Handle(thread, obj);
1974   }
1975   post_field_modification(thread,
1976                           thread->last_frame().interpreter_frame_method(),
1977                           thread->last_frame().interpreter_frame_bcp(),
1978                           klass, h_obj, fieldID, sig_type, value);
1979 }
1980 
1981 void JvmtiExport::post_raw_field_modification(JavaThread *thread, Method* method,
1982   address location, Klass* field_klass, Handle object, jfieldID field,
1983   char sig_type, jvalue *value) {
1984 
1985   if (sig_type == JVM_SIGNATURE_INT || sig_type == JVM_SIGNATURE_BOOLEAN ||
1986       sig_type == JVM_SIGNATURE_BYTE || sig_type == JVM_SIGNATURE_CHAR ||
1987       sig_type == JVM_SIGNATURE_SHORT) {
1988     // 'I' instructions are used for byte, char, short and int.
1989     // determine which it really is, and convert
1990     fieldDescriptor fd;
1991     bool found = JvmtiEnv::get_field_descriptor(field_klass, field, &fd);
1992     // should be found (if not, leave as is)
1993     if (found) {
1994       jint ival = value->i;
1995       // convert value from int to appropriate type
1996       switch (fd.field_type()) {
1997       case T_BOOLEAN:
1998         sig_type = JVM_SIGNATURE_BOOLEAN;
1999         value->i = 0; // clear it
2000         value->z = (jboolean)ival;
2001         break;
2002       case T_BYTE:
2003         sig_type = JVM_SIGNATURE_BYTE;
2004         value->i = 0; // clear it
2005         value->b = (jbyte)ival;
2006         break;
2007       case T_CHAR:
2008         sig_type = JVM_SIGNATURE_CHAR;
2009         value->i = 0; // clear it
2010         value->c = (jchar)ival;
2011         break;
2012       case T_SHORT:
2013         sig_type = JVM_SIGNATURE_SHORT;
2014         value->i = 0; // clear it
2015         value->s = (jshort)ival;
2016         break;
2017       case T_INT:
2018         // nothing to do
2019         break;
2020       default:
2021         // this is an integer instruction, should be one of above
2022         ShouldNotReachHere();
2023         break;
2024       }
2025     }
2026   }
2027 
2028   assert(sig_type != JVM_SIGNATURE_ARRAY, "array should have sig_type == 'L'");
2029   bool handle_created = false;
2030 
2031   // convert oop to JNI handle.
2032   if (sig_type == JVM_SIGNATURE_CLASS) {
2033     handle_created = true;
2034     value->l = (jobject)JNIHandles::make_local(thread, (oop)value->l);
2035   }
2036 
2037   post_field_modification(thread, method, location, field_klass, object, field, sig_type, value);
2038 
2039   // Destroy the JNI handle allocated above.
2040   if (handle_created) {
2041     JNIHandles::destroy_local(value->l);
2042   }
2043 }
2044 
2045 void JvmtiExport::post_field_modification(JavaThread *thread, Method* method,
2046   address location, Klass* field_klass, Handle object, jfieldID field,
2047   char sig_type, jvalue *value_ptr) {
2048 
2049   HandleMark hm(thread);
2050   methodHandle mh(thread, method);
2051 
2052   JvmtiThreadState *state = thread->jvmti_thread_state();
2053   if (state == NULL) {
2054     return;
2055   }
2056   EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
2057                      ("[%s] Trg Field Modification event triggered",
2058                       JvmtiTrace::safe_get_thread_name(thread)));
2059 
2060   JvmtiEnvThreadStateIterator it(state);
2061   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2062     if (ets->is_enabled(JVMTI_EVENT_FIELD_MODIFICATION)) {
2063       EVT_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
2064                    ("[%s] Evt Field Modification event sent %s.%s @ " INTX_FORMAT,
2065                     JvmtiTrace::safe_get_thread_name(thread),
2066                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
2067                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
2068                     location - mh()->code_base() ));
2069 
2070       JvmtiEnv *env = ets->get_env();
2071       JvmtiLocationEventMark jem(thread, mh, location);
2072       jclass field_jclass = jem.to_jclass(field_klass);
2073       jobject field_jobject = jem.to_jobject(object());
2074       JvmtiJavaThreadEventTransition jet(thread);
2075       jvmtiEventFieldModification callback = env->callbacks()->FieldModification;
2076       if (callback != NULL) {
2077         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2078                     jem.jni_methodID(), jem.location(),
2079                     field_jclass, field_jobject, field, sig_type, *value_ptr);
2080       }
2081     }
2082   }
2083 }
2084 
2085 void JvmtiExport::post_native_method_bind(Method* method, address* function_ptr) {
2086   JavaThread* thread = JavaThread::current();
2087   assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
2088 
2089   HandleMark hm(thread);
2090   methodHandle mh(thread, method);
2091 
2092   EVT_TRIG_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Trg Native Method Bind event triggered",
2093                       JvmtiTrace::safe_get_thread_name(thread)));
2094 
2095   if (JvmtiEventController::is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
2096     JvmtiEnvIterator it;
2097     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2098       if (env->is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
2099         EVT_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Evt Native Method Bind event sent",
2100                      JvmtiTrace::safe_get_thread_name(thread) ));
2101 
2102         JvmtiMethodEventMark jem(thread, mh);
2103         JvmtiJavaThreadEventTransition jet(thread);
2104         JNIEnv* jni_env = (env->phase() == JVMTI_PHASE_PRIMORDIAL) ? NULL : jem.jni_env();
2105         jvmtiEventNativeMethodBind callback = env->callbacks()->NativeMethodBind;
2106         if (callback != NULL) {
2107           (*callback)(env->jvmti_external(), jni_env, jem.jni_thread(),
2108                       jem.jni_methodID(), (void*)(*function_ptr), (void**)function_ptr);
2109         }
2110       }
2111     }
2112   }
2113 }
2114 
2115 // Returns a record containing inlining information for the given nmethod
2116 jvmtiCompiledMethodLoadInlineRecord* create_inline_record(nmethod* nm) {
2117   jint numstackframes = 0;
2118   jvmtiCompiledMethodLoadInlineRecord* record = (jvmtiCompiledMethodLoadInlineRecord*)NEW_RESOURCE_OBJ(jvmtiCompiledMethodLoadInlineRecord);
2119   record->header.kind = JVMTI_CMLR_INLINE_INFO;
2120   record->header.next = NULL;
2121   record->header.majorinfoversion = JVMTI_CMLR_MAJOR_VERSION_1;
2122   record->header.minorinfoversion = JVMTI_CMLR_MINOR_VERSION_0;
2123   record->numpcs = 0;
2124   for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
2125    if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
2126    record->numpcs++;
2127   }
2128   record->pcinfo = (PCStackInfo*)(NEW_RESOURCE_ARRAY(PCStackInfo, record->numpcs));
2129   int scope = 0;
2130   for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
2131     if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
2132     void* pc_address = (void*)p->real_pc(nm);
2133     assert(pc_address != NULL, "pc_address must be non-null");
2134     record->pcinfo[scope].pc = pc_address;
2135     numstackframes=0;
2136     for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2137       numstackframes++;
2138     }
2139     assert(numstackframes != 0, "numstackframes must be nonzero.");
2140     record->pcinfo[scope].methods = (jmethodID *)NEW_RESOURCE_ARRAY(jmethodID, numstackframes);
2141     record->pcinfo[scope].bcis = (jint *)NEW_RESOURCE_ARRAY(jint, numstackframes);
2142     record->pcinfo[scope].numstackframes = numstackframes;
2143     int stackframe = 0;
2144     for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2145       // 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()
2146       assert(sd->method() != NULL, "sd->method() cannot be null.");
2147       record->pcinfo[scope].methods[stackframe] = sd->method()->jmethod_id();
2148       record->pcinfo[scope].bcis[stackframe] = sd->bci();
2149       stackframe++;
2150     }
2151     scope++;
2152   }
2153   return record;
2154 }
2155 
2156 void JvmtiExport::post_compiled_method_load(nmethod *nm) {
2157   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
2158     return;
2159   }
2160   JavaThread* thread = JavaThread::current();
2161 
2162   EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2163                  ("[%s] method compile load event triggered",
2164                  JvmtiTrace::safe_get_thread_name(thread)));
2165 
2166   JvmtiEnvIterator it;
2167   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2168     post_compiled_method_load(env, nm);
2169   }
2170 }
2171 
2172 // post a COMPILED_METHOD_LOAD event for a given environment
2173 void JvmtiExport::post_compiled_method_load(JvmtiEnv* env, nmethod *nm) {
2174   if (env->phase() == JVMTI_PHASE_PRIMORDIAL || !env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
2175     return;
2176   }
2177   jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
2178   if (callback == NULL) {
2179     return;
2180   }
2181   JavaThread* thread = JavaThread::current();
2182 
2183   EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2184            ("[%s] method compile load event sent %s.%s  ",
2185             JvmtiTrace::safe_get_thread_name(thread),
2186             (nm->method() == NULL) ? "NULL" : nm->method()->klass_name()->as_C_string(),
2187             (nm->method() == NULL) ? "NULL" : nm->method()->name()->as_C_string()));
2188   ResourceMark rm(thread);
2189   HandleMark hm(thread);
2190 
2191   // Add inlining information
2192   jvmtiCompiledMethodLoadInlineRecord* inlinerecord = create_inline_record(nm);
2193   // Pass inlining information through the void pointer
2194   JvmtiCompiledMethodLoadEventMark jem(thread, nm, inlinerecord);
2195   JvmtiJavaThreadEventTransition jet(thread);
2196   (*callback)(env->jvmti_external(), jem.jni_methodID(),
2197               jem.code_size(), jem.code_data(), jem.map_length(),
2198               jem.map(), jem.compile_info());
2199 }
2200 
2201 void JvmtiExport::post_dynamic_code_generated_internal(const char *name, const void *code_begin, const void *code_end) {
2202   assert(name != NULL && name[0] != '\0', "sanity check");
2203 
2204   JavaThread* thread = JavaThread::current();
2205   // In theory everyone coming thru here is in_vm but we need to be certain
2206   // because a callee will do a vm->native transition
2207   ThreadInVMfromUnknown __tiv;
2208 
2209   EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2210                  ("[%s] method dynamic code generated event triggered",
2211                  JvmtiTrace::safe_get_thread_name(thread)));
2212   JvmtiEnvIterator it;
2213   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2214     if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2215       EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2216                 ("[%s] dynamic code generated event sent for %s",
2217                 JvmtiTrace::safe_get_thread_name(thread), name));
2218       JvmtiEventMark jem(thread);
2219       JvmtiJavaThreadEventTransition jet(thread);
2220       jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2221       jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2222       if (callback != NULL) {
2223         (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2224       }
2225     }
2226   }
2227 }
2228 
2229 void JvmtiExport::post_dynamic_code_generated(const char *name, const void *code_begin, const void *code_end) {
2230   jvmtiPhase phase = JvmtiEnv::get_phase();
2231   if (phase == JVMTI_PHASE_PRIMORDIAL || phase == JVMTI_PHASE_START) {
2232     post_dynamic_code_generated_internal(name, code_begin, code_end);
2233   } else {
2234     // It may not be safe to post the event from this thread.  Defer all
2235     // postings to the service thread so that it can perform them in a safe
2236     // context and in-order.
2237     MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
2238     JvmtiDeferredEvent event = JvmtiDeferredEvent::dynamic_code_generated_event(
2239         name, code_begin, code_end);
2240     JvmtiDeferredEventQueue::enqueue(event);
2241   }
2242 }
2243 
2244 
2245 // post a DYNAMIC_CODE_GENERATED event for a given environment
2246 // used by GenerateEvents
2247 void JvmtiExport::post_dynamic_code_generated(JvmtiEnv* env, const char *name,
2248                                               const void *code_begin, const void *code_end)
2249 {
2250   JavaThread* thread = JavaThread::current();
2251   EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2252                  ("[%s] dynamic code generated event triggered (by GenerateEvents)",
2253                   JvmtiTrace::safe_get_thread_name(thread)));
2254   if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2255     EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2256               ("[%s] dynamic code generated event sent for %s",
2257                JvmtiTrace::safe_get_thread_name(thread), name));
2258     JvmtiEventMark jem(thread);
2259     JvmtiJavaThreadEventTransition jet(thread);
2260     jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2261     jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2262     if (callback != NULL) {
2263       (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2264     }
2265   }
2266 }
2267 
2268 // post a DynamicCodeGenerated event while holding locks in the VM.
2269 void JvmtiExport::post_dynamic_code_generated_while_holding_locks(const char* name,
2270                                                                   address code_begin, address code_end)
2271 {
2272   // register the stub with the current dynamic code event collector
2273   // Cannot take safepoint here so do not use state_for to get
2274   // jvmti thread state.
2275   JvmtiThreadState* state = JavaThread::current()->jvmti_thread_state();
2276   // state can only be NULL if the current thread is exiting which
2277   // should not happen since we're trying to post an event
2278   guarantee(state != NULL, "attempt to register stub via an exiting thread");
2279   JvmtiDynamicCodeEventCollector* collector = state->get_dynamic_code_event_collector();
2280   guarantee(collector != NULL, "attempt to register stub without event collector");
2281   collector->register_stub(name, code_begin, code_end);
2282 }
2283 
2284 // Collect all the vm internally allocated objects which are visible to java world
2285 void JvmtiExport::record_vm_internal_object_allocation(oop obj) {
2286   Thread* thread = Thread::current_or_null();
2287   if (thread != NULL && thread->is_Java_thread())  {
2288     // Can not take safepoint here.
2289     NoSafepointVerifier no_sfpt;
2290     // Cannot take safepoint here so do not use state_for to get
2291     // jvmti thread state.
2292     JvmtiThreadState *state = ((JavaThread*)thread)->jvmti_thread_state();
2293     if (state != NULL) {
2294       // state is non NULL when VMObjectAllocEventCollector is enabled.
2295       JvmtiVMObjectAllocEventCollector *collector;
2296       collector = state->get_vm_object_alloc_event_collector();
2297       if (collector != NULL && collector->is_enabled()) {
2298         // Don't record classes as these will be notified via the ClassLoad
2299         // event.
2300         if (obj->klass() != SystemDictionary::Class_klass()) {
2301           collector->record_allocation(obj);
2302         }
2303       }
2304     }
2305   }
2306 }
2307 
2308 // Collect all the sampled allocated objects.
2309 void JvmtiExport::record_sampled_internal_object_allocation(oop obj) {
2310   Thread* thread = Thread::current_or_null();
2311   if (thread != NULL && thread->is_Java_thread())  {
2312     // Can not take safepoint here.
2313     NoSafepointVerifier no_sfpt;
2314     // Cannot take safepoint here so do not use state_for to get
2315     // jvmti thread state.
2316     JvmtiThreadState *state = ((JavaThread*)thread)->jvmti_thread_state();
2317     if (state != NULL) {
2318       // state is non NULL when SampledObjectAllocEventCollector is enabled.
2319       JvmtiSampledObjectAllocEventCollector *collector;
2320       collector = state->get_sampled_object_alloc_event_collector();
2321 
2322       if (collector != NULL && collector->is_enabled()) {
2323         collector->record_allocation(obj);
2324       }
2325     }
2326   }
2327 }
2328 
2329 void JvmtiExport::post_garbage_collection_finish() {
2330   Thread *thread = Thread::current(); // this event is posted from VM-Thread.
2331   EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2332                  ("[%s] garbage collection finish event triggered",
2333                   JvmtiTrace::safe_get_thread_name(thread)));
2334   JvmtiEnvIterator it;
2335   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2336     if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH)) {
2337       EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2338                 ("[%s] garbage collection finish event sent",
2339                  JvmtiTrace::safe_get_thread_name(thread)));
2340       JvmtiThreadEventTransition jet(thread);
2341       // JNIEnv is NULL here because this event is posted from VM Thread
2342       jvmtiEventGarbageCollectionFinish callback = env->callbacks()->GarbageCollectionFinish;
2343       if (callback != NULL) {
2344         (*callback)(env->jvmti_external());
2345       }
2346     }
2347   }
2348 }
2349 
2350 void JvmtiExport::post_garbage_collection_start() {
2351   Thread* thread = Thread::current(); // this event is posted from vm-thread.
2352   EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2353                  ("[%s] garbage collection start event triggered",
2354                   JvmtiTrace::safe_get_thread_name(thread)));
2355   JvmtiEnvIterator it;
2356   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2357     if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_START)) {
2358       EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2359                 ("[%s] garbage collection start event sent",
2360                  JvmtiTrace::safe_get_thread_name(thread)));
2361       JvmtiThreadEventTransition jet(thread);
2362       // JNIEnv is NULL here because this event is posted from VM Thread
2363       jvmtiEventGarbageCollectionStart callback = env->callbacks()->GarbageCollectionStart;
2364       if (callback != NULL) {
2365         (*callback)(env->jvmti_external());
2366       }
2367     }
2368   }
2369 }
2370 
2371 void JvmtiExport::post_data_dump() {
2372   Thread *thread = Thread::current();
2373   EVT_TRIG_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2374                  ("[%s] data dump request event triggered",
2375                   JvmtiTrace::safe_get_thread_name(thread)));
2376   JvmtiEnvIterator it;
2377   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2378     if (env->is_enabled(JVMTI_EVENT_DATA_DUMP_REQUEST)) {
2379       EVT_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2380                 ("[%s] data dump request event sent",
2381                  JvmtiTrace::safe_get_thread_name(thread)));
2382      JvmtiThreadEventTransition jet(thread);
2383      // JNIEnv is NULL here because this event is posted from VM Thread
2384      jvmtiEventDataDumpRequest callback = env->callbacks()->DataDumpRequest;
2385      if (callback != NULL) {
2386        (*callback)(env->jvmti_external());
2387      }
2388     }
2389   }
2390 }
2391 
2392 void JvmtiExport::post_monitor_contended_enter(JavaThread *thread, ObjectMonitor *obj_mntr) {
2393   oop object = (oop)obj_mntr->object();
2394   JvmtiThreadState *state = thread->jvmti_thread_state();
2395   if (state == NULL) {
2396     return;
2397   }
2398 
2399   HandleMark hm(thread);
2400   Handle h(thread, object);
2401 
2402   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2403                      ("[%s] monitor contended enter event triggered",
2404                       JvmtiTrace::safe_get_thread_name(thread)));
2405 
2406   JvmtiEnvThreadStateIterator it(state);
2407   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2408     if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTER)) {
2409       EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2410                    ("[%s] monitor contended enter event sent",
2411                     JvmtiTrace::safe_get_thread_name(thread)));
2412       JvmtiMonitorEventMark  jem(thread, h());
2413       JvmtiEnv *env = ets->get_env();
2414       JvmtiThreadEventTransition jet(thread);
2415       jvmtiEventMonitorContendedEnter callback = env->callbacks()->MonitorContendedEnter;
2416       if (callback != NULL) {
2417         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2418       }
2419     }
2420   }
2421 }
2422 
2423 void JvmtiExport::post_monitor_contended_entered(JavaThread *thread, ObjectMonitor *obj_mntr) {
2424   oop object = (oop)obj_mntr->object();
2425   JvmtiThreadState *state = thread->jvmti_thread_state();
2426   if (state == NULL) {
2427     return;
2428   }
2429 
2430   HandleMark hm(thread);
2431   Handle h(thread, object);
2432 
2433   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2434                      ("[%s] monitor contended entered event triggered",
2435                       JvmtiTrace::safe_get_thread_name(thread)));
2436 
2437   JvmtiEnvThreadStateIterator it(state);
2438   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2439     if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED)) {
2440       EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2441                    ("[%s] monitor contended enter event sent",
2442                     JvmtiTrace::safe_get_thread_name(thread)));
2443       JvmtiMonitorEventMark  jem(thread, h());
2444       JvmtiEnv *env = ets->get_env();
2445       JvmtiThreadEventTransition jet(thread);
2446       jvmtiEventMonitorContendedEntered callback = env->callbacks()->MonitorContendedEntered;
2447       if (callback != NULL) {
2448         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2449       }
2450     }
2451   }
2452 }
2453 
2454 void JvmtiExport::post_monitor_wait(JavaThread *thread, oop object,
2455                                           jlong timeout) {
2456   JvmtiThreadState *state = thread->jvmti_thread_state();
2457   if (state == NULL) {
2458     return;
2459   }
2460 
2461   HandleMark hm(thread);
2462   Handle h(thread, object);
2463 
2464   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2465                      ("[%s] monitor wait event triggered",
2466                       JvmtiTrace::safe_get_thread_name(thread)));
2467 
2468   JvmtiEnvThreadStateIterator it(state);
2469   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2470     if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAIT)) {
2471       EVT_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2472                    ("[%s] monitor wait event sent",
2473                     JvmtiTrace::safe_get_thread_name(thread)));
2474       JvmtiMonitorEventMark  jem(thread, h());
2475       JvmtiEnv *env = ets->get_env();
2476       JvmtiThreadEventTransition jet(thread);
2477       jvmtiEventMonitorWait callback = env->callbacks()->MonitorWait;
2478       if (callback != NULL) {
2479         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2480                     jem.jni_object(), timeout);
2481       }
2482     }
2483   }
2484 }
2485 
2486 void JvmtiExport::post_monitor_waited(JavaThread *thread, ObjectMonitor *obj_mntr, jboolean timed_out) {
2487   oop object = (oop)obj_mntr->object();
2488   JvmtiThreadState *state = thread->jvmti_thread_state();
2489   if (state == NULL) {
2490     return;
2491   }
2492 
2493   HandleMark hm(thread);
2494   Handle h(thread, object);
2495 
2496   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2497                      ("[%s] monitor waited event triggered",
2498                       JvmtiTrace::safe_get_thread_name(thread)));
2499 
2500   JvmtiEnvThreadStateIterator it(state);
2501   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2502     if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAITED)) {
2503       EVT_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2504                    ("[%s] monitor waited event sent",
2505                     JvmtiTrace::safe_get_thread_name(thread)));
2506       JvmtiMonitorEventMark  jem(thread, h());
2507       JvmtiEnv *env = ets->get_env();
2508       JvmtiThreadEventTransition jet(thread);
2509       jvmtiEventMonitorWaited callback = env->callbacks()->MonitorWaited;
2510       if (callback != NULL) {
2511         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2512                     jem.jni_object(), timed_out);
2513       }
2514     }
2515   }
2516 }
2517 
2518 void JvmtiExport::post_vm_object_alloc(JavaThread *thread, oop object) {
2519   EVT_TRIG_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Trg vm object alloc triggered",
2520                       JvmtiTrace::safe_get_thread_name(thread)));
2521   if (object == NULL) {
2522     return;
2523   }
2524   HandleMark hm(thread);
2525   Handle h(thread, object);
2526   JvmtiEnvIterator it;
2527   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2528     if (env->is_enabled(JVMTI_EVENT_VM_OBJECT_ALLOC)) {
2529       EVT_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Evt vmobject alloc sent %s",
2530                                          JvmtiTrace::safe_get_thread_name(thread),
2531                                          object==NULL? "NULL" : object->klass()->external_name()));
2532 
2533       JvmtiObjectAllocEventMark jem(thread, h());
2534       JvmtiJavaThreadEventTransition jet(thread);
2535       jvmtiEventVMObjectAlloc callback = env->callbacks()->VMObjectAlloc;
2536       if (callback != NULL) {
2537         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2538                     jem.jni_jobject(), jem.jni_class(), jem.size());
2539       }
2540     }
2541   }
2542 }
2543 
2544 void JvmtiExport::post_sampled_object_alloc(JavaThread *thread, oop object) {
2545   JvmtiThreadState *state = thread->jvmti_thread_state();
2546   if (state == NULL) {
2547     return;
2548   }
2549 
2550   EVT_TRIG_TRACE(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC,
2551                  ("[%s] Trg sampled object alloc triggered",
2552                   JvmtiTrace::safe_get_thread_name(thread)));
2553   if (object == NULL) {
2554     return;
2555   }
2556   HandleMark hm(thread);
2557   Handle h(thread, object);
2558 
2559   JvmtiEnvThreadStateIterator it(state);
2560   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2561     if (ets->is_enabled(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC)) {
2562       EVT_TRACE(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC,
2563                 ("[%s] Evt sampled object alloc sent %s",
2564                  JvmtiTrace::safe_get_thread_name(thread),
2565                  object == NULL ? "NULL" : object->klass()->external_name()));
2566 
2567       JvmtiEnv *env = ets->get_env();
2568       JvmtiObjectAllocEventMark jem(thread, h());
2569       JvmtiJavaThreadEventTransition jet(thread);
2570       jvmtiEventSampledObjectAlloc callback = env->callbacks()->SampledObjectAlloc;
2571       if (callback != NULL) {
2572         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2573                     jem.jni_jobject(), jem.jni_class(), jem.size());
2574       }
2575     }
2576   }
2577 }
2578 
2579 ////////////////////////////////////////////////////////////////////////////////////////////////
2580 
2581 void JvmtiExport::cleanup_thread(JavaThread* thread) {
2582   assert(JavaThread::current() == thread, "thread is not current");
2583   MutexLocker mu(JvmtiThreadState_lock);
2584 
2585   if (thread->jvmti_thread_state() != NULL) {
2586     // This has to happen after the thread state is removed, which is
2587     // why it is not in post_thread_end_event like its complement
2588     // Maybe both these functions should be rolled into the posts?
2589     JvmtiEventController::thread_ended(thread);
2590   }
2591 }
2592 
2593 void JvmtiExport::clear_detected_exception(JavaThread* thread) {
2594   assert(JavaThread::current() == thread, "thread is not current");
2595 
2596   JvmtiThreadState* state = thread->jvmti_thread_state();
2597   if (state != NULL) {
2598     state->clear_exception_state();
2599   }
2600 }
2601 
2602 void JvmtiExport::oops_do(OopClosure* f) {
2603   JvmtiCurrentBreakpoints::oops_do(f);
2604   JvmtiObjectAllocEventCollector::oops_do_for_all_threads(f);
2605 }
2606 
2607 void JvmtiExport::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f) {
2608   JvmtiTagMap::weak_oops_do(is_alive, f);
2609 }
2610 
2611 // Onload raw monitor transition.
2612 void JvmtiExport::transition_pending_onload_raw_monitors() {
2613   JvmtiPendingMonitors::transition_raw_monitors();
2614 }
2615 
2616 ////////////////////////////////////////////////////////////////////////////////////////////////
2617 #if INCLUDE_SERVICES
2618 // Attach is disabled if SERVICES is not included
2619 
2620 // type for the Agent_OnAttach entry point
2621 extern "C" {
2622   typedef jint (JNICALL *OnAttachEntry_t)(JavaVM*, char *, void *);
2623 }
2624 
2625 jint JvmtiExport::load_agent_library(const char *agent, const char *absParam,
2626                                      const char *options, outputStream* st) {
2627   char ebuf[1024] = {0};
2628   char buffer[JVM_MAXPATHLEN];
2629   void* library = NULL;
2630   jint result = JNI_ERR;
2631   const char *on_attach_symbols[] = AGENT_ONATTACH_SYMBOLS;
2632   size_t num_symbol_entries = ARRAY_SIZE(on_attach_symbols);
2633 
2634   // The abs paramter should be "true" or "false"
2635   bool is_absolute_path = (absParam != NULL) && (strcmp(absParam,"true")==0);
2636 
2637   // Initially marked as invalid. It will be set to valid if we can find the agent
2638   AgentLibrary *agent_lib = new AgentLibrary(agent, options, is_absolute_path, NULL);
2639 
2640   // Check for statically linked in agent. If not found then if the path is
2641   // absolute we attempt to load the library. Otherwise we try to load it
2642   // from the standard dll directory.
2643 
2644   if (!os::find_builtin_agent(agent_lib, on_attach_symbols, num_symbol_entries)) {
2645     if (is_absolute_path) {
2646       library = os::dll_load(agent, ebuf, sizeof ebuf);
2647     } else {
2648       // Try to load the agent from the standard dll directory
2649       if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
2650                              agent)) {
2651         library = os::dll_load(buffer, ebuf, sizeof ebuf);
2652       }
2653       if (library == NULL) {
2654         // not found - try OS default library path
2655         if (os::dll_build_name(buffer, sizeof(buffer), agent)) {
2656           library = os::dll_load(buffer, ebuf, sizeof ebuf);
2657         }
2658       }
2659     }
2660     if (library != NULL) {
2661       agent_lib->set_os_lib(library);
2662       agent_lib->set_valid();
2663     }
2664   }
2665   // If the library was loaded then we attempt to invoke the Agent_OnAttach
2666   // function
2667   if (agent_lib->valid()) {
2668     // Lookup the Agent_OnAttach function
2669     OnAttachEntry_t on_attach_entry = NULL;
2670     on_attach_entry = CAST_TO_FN_PTR(OnAttachEntry_t,
2671        os::find_agent_function(agent_lib, false, on_attach_symbols, num_symbol_entries));
2672     if (on_attach_entry == NULL) {
2673       // Agent_OnAttach missing - unload library
2674       if (!agent_lib->is_static_lib()) {
2675         os::dll_unload(library);
2676       }
2677       st->print_cr("%s is not available in %s",
2678                    on_attach_symbols[0], agent_lib->name());
2679       delete agent_lib;
2680     } else {
2681       // Invoke the Agent_OnAttach function
2682       JavaThread* THREAD = JavaThread::current();
2683       {
2684         extern struct JavaVM_ main_vm;
2685         JvmtiThreadEventMark jem(THREAD);
2686         JvmtiJavaThreadEventTransition jet(THREAD);
2687 
2688         result = (*on_attach_entry)(&main_vm, (char*)options, NULL);
2689       }
2690 
2691       // Agent_OnAttach may have used JNI
2692       if (HAS_PENDING_EXCEPTION) {
2693         CLEAR_PENDING_EXCEPTION;
2694       }
2695 
2696       // If OnAttach returns JNI_OK then we add it to the list of
2697       // agent libraries so that we can call Agent_OnUnload later.
2698       if (result == JNI_OK) {
2699         Arguments::add_loaded_agent(agent_lib);
2700       } else {
2701         delete agent_lib;
2702       }
2703 
2704       // Agent_OnAttach executed so completion status is JNI_OK
2705       st->print_cr("return code: %d", result);
2706       result = JNI_OK;
2707     }
2708   } else {
2709     st->print_cr("%s was not loaded.", agent);
2710     if (*ebuf != '\0') {
2711       st->print_cr("%s", ebuf);
2712     }
2713   }
2714   return result;
2715 }
2716 
2717 #endif // INCLUDE_SERVICES
2718 ////////////////////////////////////////////////////////////////////////////////////////////////
2719 
2720 // Setup current current thread for event collection.
2721 void JvmtiEventCollector::setup_jvmti_thread_state() {
2722   // set this event collector to be the current one.
2723   JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
2724   // state can only be NULL if the current thread is exiting which
2725   // should not happen since we're trying to configure for event collection
2726   guarantee(state != NULL, "exiting thread called setup_jvmti_thread_state");
2727   if (is_vm_object_alloc_event()) {
2728     JvmtiVMObjectAllocEventCollector *prev = state->get_vm_object_alloc_event_collector();
2729 
2730     // If we have a previous collector and it is disabled, it means this allocation came from a
2731     // callback induced VM Object allocation, do not register this collector then.
2732     if (prev && !prev->is_enabled()) {
2733       return;
2734     }
2735     _prev = prev;
2736     state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)this);
2737   } else if (is_dynamic_code_event()) {
2738     _prev = state->get_dynamic_code_event_collector();
2739     state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)this);
2740   } else if (is_sampled_object_alloc_event()) {
2741     JvmtiSampledObjectAllocEventCollector *prev = state->get_sampled_object_alloc_event_collector();
2742 
2743     if (prev) {
2744       // JvmtiSampledObjectAllocEventCollector wants only one active collector
2745       // enabled. This allows to have a collector detect a user code requiring
2746       // a sample in the callback.
2747       return;
2748     }
2749     state->set_sampled_object_alloc_event_collector((JvmtiSampledObjectAllocEventCollector*) this);
2750   }
2751 
2752   _unset_jvmti_thread_state = true;
2753 }
2754 
2755 // Unset current event collection in this thread and reset it with previous
2756 // collector.
2757 void JvmtiEventCollector::unset_jvmti_thread_state() {
2758   if (!_unset_jvmti_thread_state) {
2759     return;
2760   }
2761 
2762   JvmtiThreadState* state = JavaThread::current()->jvmti_thread_state();
2763   if (state != NULL) {
2764     // restore the previous event collector (if any)
2765     if (is_vm_object_alloc_event()) {
2766       if (state->get_vm_object_alloc_event_collector() == this) {
2767         state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)_prev);
2768       } else {
2769         // this thread's jvmti state was created during the scope of
2770         // the event collector.
2771       }
2772     } else if (is_dynamic_code_event()) {
2773       if (state->get_dynamic_code_event_collector() == this) {
2774         state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)_prev);
2775       } else {
2776         // this thread's jvmti state was created during the scope of
2777         // the event collector.
2778       }
2779     } else if (is_sampled_object_alloc_event()) {
2780       if (state->get_sampled_object_alloc_event_collector() == this) {
2781         state->set_sampled_object_alloc_event_collector((JvmtiSampledObjectAllocEventCollector*)_prev);
2782       } else {
2783         // this thread's jvmti state was created during the scope of
2784         // the event collector.
2785       }
2786     }
2787   }
2788 }
2789 
2790 // create the dynamic code event collector
2791 JvmtiDynamicCodeEventCollector::JvmtiDynamicCodeEventCollector() : _code_blobs(NULL) {
2792   if (JvmtiExport::should_post_dynamic_code_generated()) {
2793     setup_jvmti_thread_state();
2794   }
2795 }
2796 
2797 // iterate over any code blob descriptors collected and post a
2798 // DYNAMIC_CODE_GENERATED event to the profiler.
2799 JvmtiDynamicCodeEventCollector::~JvmtiDynamicCodeEventCollector() {
2800   assert(!JavaThread::current()->owns_locks(), "all locks must be released to post deferred events");
2801  // iterate over any code blob descriptors that we collected
2802  if (_code_blobs != NULL) {
2803    for (int i=0; i<_code_blobs->length(); i++) {
2804      JvmtiCodeBlobDesc* blob = _code_blobs->at(i);
2805      JvmtiExport::post_dynamic_code_generated(blob->name(), blob->code_begin(), blob->code_end());
2806      FreeHeap(blob);
2807    }
2808    delete _code_blobs;
2809  }
2810  unset_jvmti_thread_state();
2811 }
2812 
2813 // register a stub
2814 void JvmtiDynamicCodeEventCollector::register_stub(const char* name, address start, address end) {
2815  if (_code_blobs == NULL) {
2816    _code_blobs = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JvmtiCodeBlobDesc*>(1,true);
2817  }
2818  _code_blobs->append(new JvmtiCodeBlobDesc(name, start, end));
2819 }
2820 
2821 // Setup current thread to record vm allocated objects.
2822 JvmtiObjectAllocEventCollector::JvmtiObjectAllocEventCollector() :
2823     _allocated(NULL), _enable(false), _post_callback(NULL) {
2824 }
2825 
2826 // Post vm_object_alloc event for vm allocated objects visible to java
2827 // world.
2828 void JvmtiObjectAllocEventCollector::generate_call_for_allocated() {
2829   if (_allocated) {
2830     set_enabled(false);
2831     for (int i = 0; i < _allocated->length(); i++) {
2832       oop obj = _allocated->at(i);
2833       _post_callback(JavaThread::current(), obj);
2834     }
2835     delete _allocated, _allocated = NULL;
2836   }
2837 }
2838 
2839 void JvmtiObjectAllocEventCollector::record_allocation(oop obj) {
2840   assert(is_enabled(), "Object alloc event collector is not enabled");
2841   if (_allocated == NULL) {
2842     _allocated = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(1, true);
2843   }
2844   _allocated->push(obj);
2845 }
2846 
2847 // GC support.
2848 void JvmtiObjectAllocEventCollector::oops_do(OopClosure* f) {
2849   if (_allocated) {
2850     for(int i = _allocated->length() - 1; i >= 0; i--) {
2851       if (_allocated->at(i) != NULL) {
2852         f->do_oop(_allocated->adr_at(i));
2853       }
2854     }
2855   }
2856 }
2857 
2858 void JvmtiObjectAllocEventCollector::oops_do_for_all_threads(OopClosure* f) {
2859   // no-op if jvmti not enabled
2860   if (!JvmtiEnv::environments_might_exist()) {
2861     return;
2862   }
2863 
2864   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jthr = jtiwh.next(); ) {
2865     JvmtiThreadState *state = jthr->jvmti_thread_state();
2866     if (state != NULL) {
2867       JvmtiObjectAllocEventCollector *collector;
2868       collector = state->get_vm_object_alloc_event_collector();
2869       while (collector != NULL) {
2870         collector->oops_do(f);
2871         collector = (JvmtiObjectAllocEventCollector*) collector->get_prev();
2872       }
2873 
2874       collector = state->get_sampled_object_alloc_event_collector();
2875       while (collector != NULL) {
2876         collector->oops_do(f);
2877         collector = (JvmtiObjectAllocEventCollector*) collector->get_prev();
2878       }
2879     }
2880   }
2881 }
2882 
2883 
2884 // Disable collection of VMObjectAlloc events
2885 NoJvmtiVMObjectAllocMark::NoJvmtiVMObjectAllocMark() : _collector(NULL) {
2886   // a no-op if VMObjectAlloc event is not enabled
2887   if (!JvmtiExport::should_post_vm_object_alloc()) {
2888     return;
2889   }
2890   Thread* thread = Thread::current_or_null();
2891   if (thread != NULL && thread->is_Java_thread())  {
2892     JavaThread* current_thread = (JavaThread*)thread;
2893     JvmtiThreadState *state = current_thread->jvmti_thread_state();
2894     if (state != NULL) {
2895       JvmtiVMObjectAllocEventCollector *collector;
2896       collector = state->get_vm_object_alloc_event_collector();
2897       if (collector != NULL && collector->is_enabled()) {
2898         _collector = collector;
2899         _collector->set_enabled(false);
2900       }
2901     }
2902   }
2903 }
2904 
2905 // Re-Enable collection of VMObjectAlloc events (if previously enabled)
2906 NoJvmtiVMObjectAllocMark::~NoJvmtiVMObjectAllocMark() {
2907   if (was_enabled()) {
2908     _collector->set_enabled(true);
2909   }
2910 };
2911 
2912 // Setup current thread to record vm allocated objects.
2913 JvmtiVMObjectAllocEventCollector::JvmtiVMObjectAllocEventCollector() {
2914   if (JvmtiExport::should_post_vm_object_alloc()) {
2915     _enable = true;
2916     setup_jvmti_thread_state();
2917     _post_callback = JvmtiExport::post_vm_object_alloc;
2918   }
2919 }
2920 
2921 JvmtiVMObjectAllocEventCollector::~JvmtiVMObjectAllocEventCollector() {
2922   if (_enable) {
2923     generate_call_for_allocated();
2924   }
2925   unset_jvmti_thread_state();
2926 }
2927 
2928 bool JvmtiSampledObjectAllocEventCollector::object_alloc_is_safe_to_sample() {
2929   Thread* thread = Thread::current();
2930   // Really only sample allocations if this is a JavaThread and not the compiler
2931   // thread.
2932   if (!thread->is_Java_thread() || thread->is_Compiler_thread()) {
2933     return false;
2934   }
2935 
2936   if (MultiArray_lock->owner() == thread) {
2937     return false;
2938   }
2939   return true;
2940 }
2941 
2942 // Setup current thread to record sampled allocated objects.
2943 JvmtiSampledObjectAllocEventCollector::JvmtiSampledObjectAllocEventCollector() {
2944   if (JvmtiExport::should_post_sampled_object_alloc()) {
2945     if (!object_alloc_is_safe_to_sample()) {
2946       return;
2947     }
2948 
2949     _enable = true;
2950     setup_jvmti_thread_state();
2951     _post_callback = JvmtiExport::post_sampled_object_alloc;
2952   }
2953 }
2954 
2955 JvmtiSampledObjectAllocEventCollector::~JvmtiSampledObjectAllocEventCollector() {
2956   if (!_enable) {
2957     return;
2958   }
2959 
2960   generate_call_for_allocated();
2961   unset_jvmti_thread_state();
2962 
2963   // Unset the sampling collector as present in assertion mode only.
2964   assert(Thread::current()->is_Java_thread(),
2965          "Should always be in a Java thread");
2966 }
2967 
2968 JvmtiGCMarker::JvmtiGCMarker() {
2969   // if there aren't any JVMTI environments then nothing to do
2970   if (!JvmtiEnv::environments_might_exist()) {
2971     return;
2972   }
2973 
2974   if (JvmtiExport::should_post_garbage_collection_start()) {
2975     JvmtiExport::post_garbage_collection_start();
2976   }
2977 
2978   if (SafepointSynchronize::is_at_safepoint()) {
2979     // Do clean up tasks that need to be done at a safepoint
2980     JvmtiEnvBase::check_for_periodic_clean_up();
2981   }
2982 }
2983 
2984 JvmtiGCMarker::~JvmtiGCMarker() {
2985   // if there aren't any JVMTI environments then nothing to do
2986   if (!JvmtiEnv::environments_might_exist()) {
2987     return;
2988   }
2989 
2990   // JVMTI notify gc finish
2991   if (JvmtiExport::should_post_garbage_collection_finish()) {
2992     JvmtiExport::post_garbage_collection_finish();
2993   }
2994 }