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