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