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/attachListener.hpp"
  58 #include "services/serviceUtil.hpp"
  59 #include "utilities/macros.hpp"
  60 #if INCLUDE_ALL_GCS
  61 #include "gc/parallel/psMarkSweep.hpp"
  62 #endif // INCLUDE_ALL_GCS
  63 
  64 #ifdef JVMTI_TRACE
  65 #define EVT_TRACE(evt,out) if ((JvmtiTrace::event_trace_flags(evt) & JvmtiTrace::SHOW_EVENT_SENT) != 0) { SafeResourceMark rm; log_trace(jvmti) out; }
  66 #define EVT_TRIG_TRACE(evt,out) if ((JvmtiTrace::event_trace_flags(evt) & JvmtiTrace::SHOW_EVENT_TRIGGER) != 0) { SafeResourceMark rm; log_trace(jvmti) out; }
  67 #else
  68 #define EVT_TRIG_TRACE(evt,out)
  69 #define EVT_TRACE(evt,out)
  70 #endif
  71 
  72 ///////////////////////////////////////////////////////////////
  73 //
  74 // JvmtiEventTransition
  75 //
  76 // TO DO --
  77 //  more handle purging
  78 
  79 // Use this for JavaThreads and state is  _thread_in_vm.
  80 class JvmtiJavaThreadEventTransition : StackObj {
  81 private:
  82   ResourceMark _rm;
  83   ThreadToNativeFromVM _transition;
  84   HandleMark _hm;
  85 
  86 public:
  87   JvmtiJavaThreadEventTransition(JavaThread *thread) :
  88     _rm(),
  89     _transition(thread),
  90     _hm(thread)  {};
  91 };
  92 
  93 // For JavaThreads which are not in _thread_in_vm state
  94 // and other system threads use this.
  95 class JvmtiThreadEventTransition : StackObj {
  96 private:
  97   ResourceMark _rm;
  98   HandleMark _hm;
  99   JavaThreadState _saved_state;
 100   JavaThread *_jthread;
 101 
 102 public:
 103   JvmtiThreadEventTransition(Thread *thread) : _rm(), _hm() {
 104     if (thread->is_Java_thread()) {
 105        _jthread = (JavaThread *)thread;
 106        _saved_state = _jthread->thread_state();
 107        if (_saved_state == _thread_in_Java) {
 108          ThreadStateTransition::transition_from_java(_jthread, _thread_in_native);
 109        } else {
 110          ThreadStateTransition::transition(_jthread, _saved_state, _thread_in_native);
 111        }
 112     } else {
 113       _jthread = NULL;
 114     }
 115   }
 116 
 117   ~JvmtiThreadEventTransition() {
 118     if (_jthread != NULL)
 119       ThreadStateTransition::transition_from_native(_jthread, _saved_state);
 120   }
 121 };
 122 
 123 
 124 ///////////////////////////////////////////////////////////////
 125 //
 126 // JvmtiEventMark
 127 //
 128 
 129 class JvmtiEventMark : public StackObj {
 130 private:
 131   JavaThread *_thread;
 132   JNIEnv* _jni_env;
 133   JvmtiThreadState::ExceptionState _saved_exception_state;
 134 #if 0
 135   JNIHandleBlock* _hblock;
 136 #endif
 137 
 138 public:
 139   JvmtiEventMark(JavaThread *thread) :  _thread(thread),
 140                                         _jni_env(thread->jni_environment()),
 141                                         _saved_exception_state(JvmtiThreadState::ES_CLEARED) {
 142 #if 0
 143     _hblock = thread->active_handles();
 144     _hblock->clear_thoroughly(); // so we can be safe
 145 #else
 146     // we want to use the code above - but that needs the JNIHandle changes - later...
 147     // for now, steal JNI push local frame code
 148     JvmtiThreadState *state = thread->jvmti_thread_state();
 149     // we are before an event.
 150     // Save current jvmti thread exception state.
 151     if (state != NULL) {
 152       _saved_exception_state = state->get_exception_state();
 153     }
 154 
 155     JNIHandleBlock* old_handles = thread->active_handles();
 156     JNIHandleBlock* new_handles = JNIHandleBlock::allocate_block(thread);
 157     assert(new_handles != NULL, "should not be NULL");
 158     new_handles->set_pop_frame_link(old_handles);
 159     thread->set_active_handles(new_handles);
 160 #endif
 161     assert(thread == JavaThread::current(), "thread must be current!");
 162     thread->frame_anchor()->make_walkable(thread);
 163   };
 164 
 165   ~JvmtiEventMark() {
 166 #if 0
 167     _hblock->clear(); // for consistency with future correct behavior
 168 #else
 169     // we want to use the code above - but that needs the JNIHandle changes - later...
 170     // for now, steal JNI pop local frame code
 171     JNIHandleBlock* old_handles = _thread->active_handles();
 172     JNIHandleBlock* new_handles = old_handles->pop_frame_link();
 173     assert(new_handles != NULL, "should not be NULL");
 174     _thread->set_active_handles(new_handles);
 175     // Note that we set the pop_frame_link to NULL explicitly, otherwise
 176     // the release_block call will release the blocks.
 177     old_handles->set_pop_frame_link(NULL);
 178     JNIHandleBlock::release_block(old_handles, _thread); // may block
 179 #endif
 180 
 181     JvmtiThreadState* state = _thread->jvmti_thread_state();
 182     // we are continuing after an event.
 183     if (state != NULL) {
 184       // Restore the jvmti thread exception state.
 185       state->restore_exception_state(_saved_exception_state);
 186     }
 187   }
 188 
 189 #if 0
 190   jobject to_jobject(oop obj) { return obj == NULL? NULL : _hblock->allocate_handle_fast(obj); }
 191 #else
 192   // we want to use the code above - but that needs the JNIHandle changes - later...
 193   // for now, use regular make_local
 194   jobject to_jobject(oop obj) { return JNIHandles::make_local(_thread,obj); }
 195 #endif
 196 
 197   jclass to_jclass(Klass* klass) { return (klass == NULL ? NULL : (jclass)to_jobject(klass->java_mirror())); }
 198 
 199   jmethodID to_jmethodID(methodHandle method) { return method->jmethod_id(); }
 200 
 201   JNIEnv* jni_env() { return _jni_env; }
 202 };
 203 
 204 class JvmtiThreadEventMark : public JvmtiEventMark {
 205 private:
 206   jthread _jt;
 207 
 208 public:
 209   JvmtiThreadEventMark(JavaThread *thread) :
 210     JvmtiEventMark(thread) {
 211     _jt = (jthread)(to_jobject(thread->threadObj()));
 212   };
 213  jthread jni_thread() { return _jt; }
 214 };
 215 
 216 class JvmtiClassEventMark : public JvmtiThreadEventMark {
 217 private:
 218   jclass _jc;
 219 
 220 public:
 221   JvmtiClassEventMark(JavaThread *thread, Klass* klass) :
 222     JvmtiThreadEventMark(thread) {
 223     _jc = to_jclass(klass);
 224   };
 225   jclass jni_class() { return _jc; }
 226 };
 227 
 228 class JvmtiMethodEventMark : public JvmtiThreadEventMark {
 229 private:
 230   jmethodID _mid;
 231 
 232 public:
 233   JvmtiMethodEventMark(JavaThread *thread, methodHandle method) :
 234     JvmtiThreadEventMark(thread),
 235     _mid(to_jmethodID(method)) {};
 236   jmethodID jni_methodID() { return _mid; }
 237 };
 238 
 239 class JvmtiLocationEventMark : public JvmtiMethodEventMark {
 240 private:
 241   jlocation _loc;
 242 
 243 public:
 244   JvmtiLocationEventMark(JavaThread *thread, methodHandle method, address location) :
 245     JvmtiMethodEventMark(thread, method),
 246     _loc(location - method->code_base()) {};
 247   jlocation location() { return _loc; }
 248 };
 249 
 250 class JvmtiExceptionEventMark : public JvmtiLocationEventMark {
 251 private:
 252   jobject _exc;
 253 
 254 public:
 255   JvmtiExceptionEventMark(JavaThread *thread, methodHandle method, address location, Handle exception) :
 256     JvmtiLocationEventMark(thread, method, location),
 257     _exc(to_jobject(exception())) {};
 258   jobject exception() { return _exc; }
 259 };
 260 
 261 class JvmtiClassFileLoadEventMark : public JvmtiThreadEventMark {
 262 private:
 263   const char *_class_name;
 264   jobject _jloader;
 265   jobject _protection_domain;
 266   jclass  _class_being_redefined;
 267 
 268 public:
 269   JvmtiClassFileLoadEventMark(JavaThread *thread, Symbol* name,
 270      Handle class_loader, Handle prot_domain, Klass* class_being_redefined) : JvmtiThreadEventMark(thread) {
 271       _class_name = name != NULL? name->as_utf8() : NULL;
 272       _jloader = (jobject)to_jobject(class_loader());
 273       _protection_domain = (jobject)to_jobject(prot_domain());
 274       if (class_being_redefined == NULL) {
 275         _class_being_redefined = NULL;
 276       } else {
 277         _class_being_redefined = (jclass)to_jclass(class_being_redefined);
 278       }
 279   };
 280   const char *class_name() {
 281     return _class_name;
 282   }
 283   jobject jloader() {
 284     return _jloader;
 285   }
 286   jobject protection_domain() {
 287     return _protection_domain;
 288   }
 289   jclass class_being_redefined() {
 290     return _class_being_redefined;
 291   }
 292 };
 293 
 294 //////////////////////////////////////////////////////////////////////////////
 295 
 296 int               JvmtiExport::_field_access_count                        = 0;
 297 int               JvmtiExport::_field_modification_count                  = 0;
 298 
 299 bool              JvmtiExport::_can_access_local_variables                = false;
 300 bool              JvmtiExport::_can_hotswap_or_post_breakpoint            = false;
 301 bool              JvmtiExport::_can_modify_any_class                      = false;
 302 bool              JvmtiExport::_can_walk_any_space                        = false;
 303 
 304 bool              JvmtiExport::_has_redefined_a_class                     = false;
 305 bool              JvmtiExport::_all_dependencies_are_recorded             = false;
 306 
 307 //
 308 // field access management
 309 //
 310 
 311 // interpreter generator needs the address of the counter
 312 address JvmtiExport::get_field_access_count_addr() {
 313   // We don't grab a lock because we don't want to
 314   // serialize field access between all threads. This means that a
 315   // thread on another processor can see the wrong count value and
 316   // may either miss making a needed call into post_field_access()
 317   // or will make an unneeded call into post_field_access(). We pay
 318   // this price to avoid slowing down the VM when we aren't watching
 319   // field accesses.
 320   // Other access/mutation safe by virtue of being in VM state.
 321   return (address)(&_field_access_count);
 322 }
 323 
 324 //
 325 // field modification management
 326 //
 327 
 328 // interpreter generator needs the address of the counter
 329 address JvmtiExport::get_field_modification_count_addr() {
 330   // We don't grab a lock because we don't
 331   // want to serialize field modification between all threads. This
 332   // means that a thread on another processor can see the wrong
 333   // count value and may either miss making a needed call into
 334   // post_field_modification() or will make an unneeded call into
 335   // post_field_modification(). We pay this price to avoid slowing
 336   // down the VM when we aren't watching field modifications.
 337   // Other access/mutation safe by virtue of being in VM state.
 338   return (address)(&_field_modification_count);
 339 }
 340 
 341 
 342 ///////////////////////////////////////////////////////////////
 343 // Functions needed by java.lang.instrument for starting up javaagent.
 344 ///////////////////////////////////////////////////////////////
 345 
 346 jint
 347 JvmtiExport::get_jvmti_interface(JavaVM *jvm, void **penv, jint version) {
 348   // The JVMTI_VERSION_INTERFACE_JVMTI part of the version number
 349   // has already been validated in JNI GetEnv().
 350   int major, minor, micro;
 351 
 352   // micro version doesn't matter here (yet?)
 353   decode_version_values(version, &major, &minor, &micro);
 354   switch (major) {
 355     case 1:
 356       switch (minor) {
 357         case 0:  // version 1.0.<micro> is recognized
 358         case 1:  // version 1.1.<micro> is recognized
 359         case 2:  // version 1.2.<micro> is recognized
 360           break;
 361 
 362         default:
 363           return JNI_EVERSION;  // unsupported minor version number
 364       }
 365       break;
 366     case 9:
 367       switch (minor) {
 368         case 0:  // version 9.0.<micro> is recognized
 369           break;
 370         default:
 371           return JNI_EVERSION;  // unsupported minor version number
 372       }
 373       break;
 374     default:
 375       return JNI_EVERSION;  // unsupported major version number
 376   }
 377 
 378   if (JvmtiEnv::get_phase() == JVMTI_PHASE_LIVE) {
 379     JavaThread* current_thread = JavaThread::current();
 380     // transition code: native to VM
 381     ThreadInVMfromNative __tiv(current_thread);
 382     VM_ENTRY_BASE(jvmtiEnv*, JvmtiExport::get_jvmti_interface, current_thread)
 383     debug_only(VMNativeEntryWrapper __vew;)
 384 
 385     JvmtiEnv *jvmti_env = JvmtiEnv::create_a_jvmti(version);
 386     *penv = jvmti_env->jvmti_external();  // actual type is jvmtiEnv* -- not to be confused with JvmtiEnv*
 387     return JNI_OK;
 388 
 389   } else if (JvmtiEnv::get_phase() == JVMTI_PHASE_ONLOAD) {
 390     // not live, no thread to transition
 391     JvmtiEnv *jvmti_env = JvmtiEnv::create_a_jvmti(version);
 392     *penv = jvmti_env->jvmti_external();  // actual type is jvmtiEnv* -- not to be confused with JvmtiEnv*
 393     return JNI_OK;
 394 
 395   } else {
 396     // Called at the wrong time
 397     *penv = NULL;
 398     return JNI_EDETACHED;
 399   }
 400 }
 401 
 402 void
 403 JvmtiExport::add_default_read_edges(Handle h_module, TRAPS) {
 404   if (!Universe::is_module_initialized()) {
 405     return; // extra safety
 406   }
 407   assert(!h_module.is_null(), "module should always be set");
 408 
 409   // Invoke the transformedByAgent method
 410   JavaValue result(T_VOID);
 411   JavaCalls::call_static(&result,
 412                          SystemDictionary::module_Modules_klass(),
 413                          vmSymbols::transformedByAgent_name(),
 414                          vmSymbols::transformedByAgent_signature(),
 415                          h_module,
 416                          THREAD);
 417 
 418   if (HAS_PENDING_EXCEPTION) {
 419     LogTarget(Trace, jvmti) log;
 420     LogStreamCHeap log_stream(log);
 421     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 422     log_stream.cr();
 423     CLEAR_PENDING_EXCEPTION;
 424     return;
 425   }
 426 }
 427 
 428 jvmtiError
 429 JvmtiExport::add_module_reads(Handle module, Handle to_module, TRAPS) {
 430   if (!Universe::is_module_initialized()) {
 431     return JVMTI_ERROR_NONE; // extra safety
 432   }
 433   assert(!module.is_null(), "module should always be set");
 434   assert(!to_module.is_null(), "to_module should always be set");
 435 
 436   // Invoke the addReads method
 437   JavaValue result(T_VOID);
 438   JavaCalls::call_static(&result,
 439                          SystemDictionary::module_Modules_klass(),
 440                          vmSymbols::addReads_name(),
 441                          vmSymbols::addReads_signature(),
 442                          module,
 443                          to_module,
 444                          THREAD);
 445 
 446   if (HAS_PENDING_EXCEPTION) {
 447     LogTarget(Trace, jvmti) log;
 448     LogStreamCHeap log_stream(log);
 449     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 450     log_stream.cr();
 451     CLEAR_PENDING_EXCEPTION;
 452     return JVMTI_ERROR_INTERNAL;
 453   }
 454   return JVMTI_ERROR_NONE;
 455 }
 456 
 457 jvmtiError
 458 JvmtiExport::add_module_exports(Handle module, Handle pkg_name, Handle to_module, TRAPS) {
 459   if (!Universe::is_module_initialized()) {
 460     return JVMTI_ERROR_NONE; // extra safety
 461   }
 462   assert(!module.is_null(), "module should always be set");
 463   assert(!to_module.is_null(), "to_module should always be set");
 464   assert(!pkg_name.is_null(), "pkg_name should always be set");
 465 
 466   // Invoke the addExports method
 467   JavaValue result(T_VOID);
 468   JavaCalls::call_static(&result,
 469                          SystemDictionary::module_Modules_klass(),
 470                          vmSymbols::addExports_name(),
 471                          vmSymbols::addExports_signature(),
 472                          module,
 473                          pkg_name,
 474                          to_module,
 475                          THREAD);
 476 
 477   if (HAS_PENDING_EXCEPTION) {
 478     Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
 479     LogTarget(Trace, jvmti) log;
 480     LogStreamCHeap log_stream(log);
 481     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 482     log_stream.cr();
 483     CLEAR_PENDING_EXCEPTION;
 484     if (ex_name == vmSymbols::java_lang_IllegalArgumentException()) {
 485       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 486     }
 487     return JVMTI_ERROR_INTERNAL;
 488   }
 489   return JVMTI_ERROR_NONE;
 490 }
 491 
 492 jvmtiError
 493 JvmtiExport::add_module_opens(Handle module, Handle pkg_name, Handle to_module, TRAPS) {
 494   if (!Universe::is_module_initialized()) {
 495     return JVMTI_ERROR_NONE; // extra safety
 496   }
 497   assert(!module.is_null(), "module should always be set");
 498   assert(!to_module.is_null(), "to_module should always be set");
 499   assert(!pkg_name.is_null(), "pkg_name should always be set");
 500 
 501   // Invoke the addOpens method
 502   JavaValue result(T_VOID);
 503   JavaCalls::call_static(&result,
 504                          SystemDictionary::module_Modules_klass(),
 505                          vmSymbols::addOpens_name(),
 506                          vmSymbols::addExports_signature(),
 507                          module,
 508                          pkg_name,
 509                          to_module,
 510                          THREAD);
 511 
 512   if (HAS_PENDING_EXCEPTION) {
 513     Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
 514     LogTarget(Trace, jvmti) log;
 515     LogStreamCHeap log_stream(log);
 516     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 517     log_stream.cr();
 518     CLEAR_PENDING_EXCEPTION;
 519     if (ex_name == vmSymbols::java_lang_IllegalArgumentException()) {
 520       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 521     }
 522     return JVMTI_ERROR_INTERNAL;
 523   }
 524   return JVMTI_ERROR_NONE;
 525 }
 526 
 527 jvmtiError
 528 JvmtiExport::add_module_uses(Handle module, Handle service, TRAPS) {
 529   if (!Universe::is_module_initialized()) {
 530     return JVMTI_ERROR_NONE; // extra safety
 531   }
 532   assert(!module.is_null(), "module should always be set");
 533   assert(!service.is_null(), "service should always be set");
 534 
 535   // Invoke the addUses method
 536   JavaValue result(T_VOID);
 537   JavaCalls::call_static(&result,
 538                          SystemDictionary::module_Modules_klass(),
 539                          vmSymbols::addUses_name(),
 540                          vmSymbols::addUses_signature(),
 541                          module,
 542                          service,
 543                          THREAD);
 544 
 545   if (HAS_PENDING_EXCEPTION) {
 546     LogTarget(Trace, jvmti) log;
 547     LogStreamCHeap log_stream(log);
 548     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 549     log_stream.cr();
 550     CLEAR_PENDING_EXCEPTION;
 551     return JVMTI_ERROR_INTERNAL;
 552   }
 553   return JVMTI_ERROR_NONE;
 554 }
 555 
 556 jvmtiError
 557 JvmtiExport::add_module_provides(Handle module, Handle service, Handle impl_class, TRAPS) {
 558   if (!Universe::is_module_initialized()) {
 559     return JVMTI_ERROR_NONE; // extra safety
 560   }
 561   assert(!module.is_null(), "module should always be set");
 562   assert(!service.is_null(), "service should always be set");
 563   assert(!impl_class.is_null(), "impl_class should always be set");
 564 
 565   // Invoke the addProvides method
 566   JavaValue result(T_VOID);
 567   JavaCalls::call_static(&result,
 568                          SystemDictionary::module_Modules_klass(),
 569                          vmSymbols::addProvides_name(),
 570                          vmSymbols::addProvides_signature(),
 571                          module,
 572                          service,
 573                          impl_class,
 574                          THREAD);
 575 
 576   if (HAS_PENDING_EXCEPTION) {
 577     LogTarget(Trace, jvmti) log;
 578     LogStreamCHeap log_stream(log);
 579     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 580     log_stream.cr();
 581     CLEAR_PENDING_EXCEPTION;
 582     return JVMTI_ERROR_INTERNAL;
 583   }
 584   return JVMTI_ERROR_NONE;
 585 }
 586 
 587 void
 588 JvmtiExport::decode_version_values(jint version, int * major, int * minor,
 589                                    int * micro) {
 590   *major = (version & JVMTI_VERSION_MASK_MAJOR) >> JVMTI_VERSION_SHIFT_MAJOR;
 591   *minor = (version & JVMTI_VERSION_MASK_MINOR) >> JVMTI_VERSION_SHIFT_MINOR;
 592   *micro = (version & JVMTI_VERSION_MASK_MICRO) >> JVMTI_VERSION_SHIFT_MICRO;
 593 }
 594 
 595 void JvmtiExport::enter_primordial_phase() {
 596   JvmtiEnvBase::set_phase(JVMTI_PHASE_PRIMORDIAL);
 597 }
 598 
 599 void JvmtiExport::enter_early_start_phase() {
 600   JvmtiManageCapabilities::recompute_always_capabilities();
 601   set_early_vmstart_recorded(true);
 602 }
 603 
 604 void JvmtiExport::enter_start_phase() {
 605   JvmtiManageCapabilities::recompute_always_capabilities();
 606   JvmtiEnvBase::set_phase(JVMTI_PHASE_START);
 607 }
 608 
 609 void JvmtiExport::enter_onload_phase() {
 610   JvmtiEnvBase::set_phase(JVMTI_PHASE_ONLOAD);
 611 }
 612 
 613 void JvmtiExport::enter_live_phase() {
 614   JvmtiEnvBase::set_phase(JVMTI_PHASE_LIVE);
 615 }
 616 
 617 //
 618 // JVMTI events that the VM posts to the debugger and also startup agent
 619 // and call the agent's premain() for java.lang.instrument.
 620 //
 621 
 622 void JvmtiExport::post_early_vm_start() {
 623   EVT_TRIG_TRACE(JVMTI_EVENT_VM_START, ("Trg Early VM start event triggered" ));
 624 
 625   // can now enable some events
 626   JvmtiEventController::vm_start();
 627 
 628   JvmtiEnvIterator it;
 629   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 630     // Only early vmstart envs post early VMStart event
 631     if (env->early_vmstart_env() && env->is_enabled(JVMTI_EVENT_VM_START)) {
 632       EVT_TRACE(JVMTI_EVENT_VM_START, ("Evt Early VM start event sent" ));
 633       JavaThread *thread  = JavaThread::current();
 634       JvmtiThreadEventMark jem(thread);
 635       JvmtiJavaThreadEventTransition jet(thread);
 636       jvmtiEventVMStart callback = env->callbacks()->VMStart;
 637       if (callback != NULL) {
 638         (*callback)(env->jvmti_external(), jem.jni_env());
 639       }
 640     }
 641   }
 642 }
 643 
 644 void JvmtiExport::post_vm_start() {
 645   EVT_TRIG_TRACE(JVMTI_EVENT_VM_START, ("Trg VM start event triggered" ));
 646 
 647   // can now enable some events
 648   JvmtiEventController::vm_start();
 649 
 650   JvmtiEnvIterator it;
 651   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 652     // Early vmstart envs do not post normal VMStart event
 653     if (!env->early_vmstart_env() && env->is_enabled(JVMTI_EVENT_VM_START)) {
 654       EVT_TRACE(JVMTI_EVENT_VM_START, ("Evt VM start event sent" ));
 655 
 656       JavaThread *thread  = JavaThread::current();
 657       JvmtiThreadEventMark jem(thread);
 658       JvmtiJavaThreadEventTransition jet(thread);
 659       jvmtiEventVMStart callback = env->callbacks()->VMStart;
 660       if (callback != NULL) {
 661         (*callback)(env->jvmti_external(), jem.jni_env());
 662       }
 663     }
 664   }
 665 }
 666 
 667 
 668 void JvmtiExport::post_vm_initialized() {
 669   EVT_TRIG_TRACE(JVMTI_EVENT_VM_INIT, ("Trg VM init event triggered" ));
 670 
 671   // can now enable events
 672   JvmtiEventController::vm_init();
 673 
 674   JvmtiEnvIterator it;
 675   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 676     if (env->is_enabled(JVMTI_EVENT_VM_INIT)) {
 677       EVT_TRACE(JVMTI_EVENT_VM_INIT, ("Evt VM init event sent" ));
 678 
 679       JavaThread *thread  = JavaThread::current();
 680       JvmtiThreadEventMark jem(thread);
 681       JvmtiJavaThreadEventTransition jet(thread);
 682       jvmtiEventVMInit callback = env->callbacks()->VMInit;
 683       if (callback != NULL) {
 684         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
 685       }
 686     }
 687   }
 688 }
 689 
 690 
 691 void JvmtiExport::post_vm_death() {
 692   EVT_TRIG_TRACE(JVMTI_EVENT_VM_DEATH, ("Trg VM death event triggered" ));
 693 
 694   JvmtiEnvIterator it;
 695   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 696     if (env->is_enabled(JVMTI_EVENT_VM_DEATH)) {
 697       EVT_TRACE(JVMTI_EVENT_VM_DEATH, ("Evt VM death event sent" ));
 698 
 699       JavaThread *thread  = JavaThread::current();
 700       JvmtiEventMark jem(thread);
 701       JvmtiJavaThreadEventTransition jet(thread);
 702       jvmtiEventVMDeath callback = env->callbacks()->VMDeath;
 703       if (callback != NULL) {
 704         (*callback)(env->jvmti_external(), jem.jni_env());
 705       }
 706     }
 707   }
 708 
 709   JvmtiEnvBase::set_phase(JVMTI_PHASE_DEAD);
 710   JvmtiEventController::vm_death();
 711 }
 712 
 713 char**
 714 JvmtiExport::get_all_native_method_prefixes(int* count_ptr) {
 715   // Have to grab JVMTI thread state lock to be sure environment doesn't
 716   // go away while we iterate them.  No locks during VM bring-up.
 717   if (Threads::number_of_threads() == 0 || SafepointSynchronize::is_at_safepoint()) {
 718     return JvmtiEnvBase::get_all_native_method_prefixes(count_ptr);
 719   } else {
 720     MutexLocker mu(JvmtiThreadState_lock);
 721     return JvmtiEnvBase::get_all_native_method_prefixes(count_ptr);
 722   }
 723 }
 724 
 725 class JvmtiClassFileLoadHookPoster : public StackObj {
 726  private:
 727   Symbol*            _h_name;
 728   Handle               _class_loader;
 729   Handle               _h_protection_domain;
 730   unsigned char **     _data_ptr;
 731   unsigned char **     _end_ptr;
 732   JavaThread *         _thread;
 733   jint                 _curr_len;
 734   unsigned char *      _curr_data;
 735   JvmtiEnv *           _curr_env;
 736   JvmtiCachedClassFileData ** _cached_class_file_ptr;
 737   JvmtiThreadState *   _state;
 738   Klass*               _class_being_redefined;
 739   JvmtiClassLoadKind   _load_kind;
 740   bool                 _has_been_modified;
 741 
 742  public:
 743   inline JvmtiClassFileLoadHookPoster(Symbol* h_name, Handle class_loader,
 744                                       Handle h_protection_domain,
 745                                       unsigned char **data_ptr, unsigned char **end_ptr,
 746                                       JvmtiCachedClassFileData **cache_ptr) {
 747     _h_name = h_name;
 748     _class_loader = class_loader;
 749     _h_protection_domain = h_protection_domain;
 750     _data_ptr = data_ptr;
 751     _end_ptr = end_ptr;
 752     _thread = JavaThread::current();
 753     _curr_len = *end_ptr - *data_ptr;
 754     _curr_data = *data_ptr;
 755     _curr_env = NULL;
 756     _cached_class_file_ptr = cache_ptr;
 757     _has_been_modified = false;
 758 
 759     _state = _thread->jvmti_thread_state();
 760     if (_state != NULL) {
 761       _class_being_redefined = _state->get_class_being_redefined();
 762       _load_kind = _state->get_class_load_kind();
 763       Klass* klass = (_class_being_redefined == NULL) ? NULL : _class_being_redefined;
 764       if (_load_kind != jvmti_class_load_kind_load && klass != NULL) {
 765         ModuleEntry* module_entry = InstanceKlass::cast(klass)->module();
 766         assert(module_entry != NULL, "module_entry should always be set");
 767         if (module_entry->is_named() &&
 768             module_entry->module() != NULL &&
 769             !module_entry->has_default_read_edges()) {
 770           if (!module_entry->set_has_default_read_edges()) {
 771             // We won a potential race.
 772             // Add read edges to the unnamed modules of the bootstrap and app class loaders
 773             Handle class_module(_thread, JNIHandles::resolve(module_entry->module())); // Obtain j.l.r.Module
 774             JvmtiExport::add_default_read_edges(class_module, _thread);
 775           }
 776         }
 777       }
 778       // Clear class_being_redefined flag here. The action
 779       // from agent handler could generate a new class file load
 780       // hook event and if it is not cleared the new event generated
 781       // from regular class file load could have this stale redefined
 782       // class handle info.
 783       _state->clear_class_being_redefined();
 784     } else {
 785       // redefine and retransform will always set the thread state
 786       _class_being_redefined = NULL;
 787       _load_kind = jvmti_class_load_kind_load;
 788     }
 789   }
 790 
 791   void post() {
 792     post_all_envs();
 793     copy_modified_data();
 794   }
 795 
 796   bool has_been_modified() { return _has_been_modified; }
 797 
 798  private:
 799   void post_all_envs() {
 800     if (_load_kind != jvmti_class_load_kind_retransform) {
 801       // for class load and redefine,
 802       // call the non-retransformable agents
 803       JvmtiEnvIterator it;
 804       for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 805         if (!env->is_retransformable() && env->is_enabled(JVMTI_EVENT_CLASS_FILE_LOAD_HOOK)) {
 806           // non-retransformable agents cannot retransform back,
 807           // so no need to cache the original class file bytes
 808           post_to_env(env, false);
 809         }
 810       }
 811     }
 812     JvmtiEnvIterator it;
 813     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 814       // retransformable agents get all events
 815       if (env->is_retransformable() && env->is_enabled(JVMTI_EVENT_CLASS_FILE_LOAD_HOOK)) {
 816         // retransformable agents need to cache the original class file
 817         // bytes if changes are made via the ClassFileLoadHook
 818         post_to_env(env, true);
 819       }
 820     }
 821   }
 822 
 823   void post_to_env(JvmtiEnv* env, bool caching_needed) {
 824     if (env->phase() == JVMTI_PHASE_PRIMORDIAL && !env->early_class_hook_env()) {
 825       return;
 826     }
 827     unsigned char *new_data = NULL;
 828     jint new_len = 0;
 829     JvmtiClassFileLoadEventMark jem(_thread, _h_name, _class_loader,
 830                                     _h_protection_domain,
 831                                     _class_being_redefined);
 832     JvmtiJavaThreadEventTransition jet(_thread);
 833     jvmtiEventClassFileLoadHook callback = env->callbacks()->ClassFileLoadHook;
 834     if (callback != NULL) {
 835       (*callback)(env->jvmti_external(), jem.jni_env(),
 836                   jem.class_being_redefined(),
 837                   jem.jloader(), jem.class_name(),
 838                   jem.protection_domain(),
 839                   _curr_len, _curr_data,
 840                   &new_len, &new_data);
 841     }
 842     if (new_data != NULL) {
 843       // this agent has modified class data.
 844       _has_been_modified = true;
 845       if (caching_needed && *_cached_class_file_ptr == NULL) {
 846         // data has been changed by the new retransformable agent
 847         // and it hasn't already been cached, cache it
 848         JvmtiCachedClassFileData *p;
 849         p = (JvmtiCachedClassFileData *)os::malloc(
 850           offset_of(JvmtiCachedClassFileData, data) + _curr_len, mtInternal);
 851         if (p == NULL) {
 852           vm_exit_out_of_memory(offset_of(JvmtiCachedClassFileData, data) + _curr_len,
 853             OOM_MALLOC_ERROR,
 854             "unable to allocate cached copy of original class bytes");
 855         }
 856         p->length = _curr_len;
 857         memcpy(p->data, _curr_data, _curr_len);
 858         *_cached_class_file_ptr = p;
 859       }
 860 
 861       if (_curr_data != *_data_ptr) {
 862         // curr_data is previous agent modified class data.
 863         // And this has been changed by the new agent so
 864         // we can delete it now.
 865         _curr_env->Deallocate(_curr_data);
 866       }
 867 
 868       // Class file data has changed by the current agent.
 869       _curr_data = new_data;
 870       _curr_len = new_len;
 871       // Save the current agent env we need this to deallocate the
 872       // memory allocated by this agent.
 873       _curr_env = env;
 874     }
 875   }
 876 
 877   void copy_modified_data() {
 878     // if one of the agent has modified class file data.
 879     // Copy modified class data to new resources array.
 880     if (_curr_data != *_data_ptr) {
 881       *_data_ptr = NEW_RESOURCE_ARRAY(u1, _curr_len);
 882       memcpy(*_data_ptr, _curr_data, _curr_len);
 883       *_end_ptr = *_data_ptr + _curr_len;
 884       _curr_env->Deallocate(_curr_data);
 885     }
 886   }
 887 };
 888 
 889 bool JvmtiExport::_should_post_class_file_load_hook = false;
 890 
 891 // this entry is for class file load hook on class load, redefine and retransform
 892 bool JvmtiExport::post_class_file_load_hook(Symbol* h_name,
 893                                             Handle class_loader,
 894                                             Handle h_protection_domain,
 895                                             unsigned char **data_ptr,
 896                                             unsigned char **end_ptr,
 897                                             JvmtiCachedClassFileData **cache_ptr) {
 898   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
 899     return false;
 900   }
 901 
 902   JvmtiClassFileLoadHookPoster poster(h_name, class_loader,
 903                                       h_protection_domain,
 904                                       data_ptr, end_ptr,
 905                                       cache_ptr);
 906   poster.post();
 907   return poster.has_been_modified();
 908 }
 909 
 910 void JvmtiExport::report_unsupported(bool on) {
 911   // If any JVMTI service is turned on, we need to exit before native code
 912   // tries to access nonexistant services.
 913   if (on) {
 914     vm_exit_during_initialization("Java Kernel does not support JVMTI.");
 915   }
 916 }
 917 
 918 
 919 static inline Klass* oop_to_klass(oop obj) {
 920   Klass* k = obj->klass();
 921 
 922   // if the object is a java.lang.Class then return the java mirror
 923   if (k == SystemDictionary::Class_klass()) {
 924     if (!java_lang_Class::is_primitive(obj)) {
 925       k = java_lang_Class::as_Klass(obj);
 926       assert(k != NULL, "class for non-primitive mirror must exist");
 927     }
 928   }
 929   return k;
 930 }
 931 
 932 class JvmtiVMObjectAllocEventMark : public JvmtiClassEventMark  {
 933  private:
 934    jobject _jobj;
 935    jlong    _size;
 936  public:
 937    JvmtiVMObjectAllocEventMark(JavaThread *thread, oop obj) : JvmtiClassEventMark(thread, oop_to_klass(obj)) {
 938      _jobj = (jobject)to_jobject(obj);
 939      _size = obj->size() * wordSize;
 940    };
 941    jobject jni_jobject() { return _jobj; }
 942    jlong size() { return _size; }
 943 };
 944 
 945 class JvmtiCompiledMethodLoadEventMark : public JvmtiMethodEventMark {
 946  private:
 947   jint _code_size;
 948   const void *_code_data;
 949   jint _map_length;
 950   jvmtiAddrLocationMap *_map;
 951   const void *_compile_info;
 952  public:
 953   JvmtiCompiledMethodLoadEventMark(JavaThread *thread, nmethod *nm, void* compile_info_ptr = NULL)
 954           : JvmtiMethodEventMark(thread,methodHandle(thread, nm->method())) {
 955     _code_data = nm->insts_begin();
 956     _code_size = nm->insts_size();
 957     _compile_info = compile_info_ptr; // Set void pointer of compiledMethodLoad Event. Default value is NULL.
 958     JvmtiCodeBlobEvents::build_jvmti_addr_location_map(nm, &_map, &_map_length);
 959   }
 960   ~JvmtiCompiledMethodLoadEventMark() {
 961      FREE_C_HEAP_ARRAY(jvmtiAddrLocationMap, _map);
 962   }
 963 
 964   jint code_size() { return _code_size; }
 965   const void *code_data() { return _code_data; }
 966   jint map_length() { return _map_length; }
 967   const jvmtiAddrLocationMap* map() { return _map; }
 968   const void *compile_info() { return _compile_info; }
 969 };
 970 
 971 
 972 
 973 class JvmtiMonitorEventMark : public JvmtiThreadEventMark {
 974 private:
 975   jobject _jobj;
 976 public:
 977   JvmtiMonitorEventMark(JavaThread *thread, oop object)
 978           : JvmtiThreadEventMark(thread){
 979      _jobj = to_jobject(object);
 980   }
 981   jobject jni_object() { return _jobj; }
 982 };
 983 
 984 ///////////////////////////////////////////////////////////////
 985 //
 986 // pending CompiledMethodUnload support
 987 //
 988 
 989 void JvmtiExport::post_compiled_method_unload(
 990        jmethodID method, const void *code_begin) {
 991   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
 992     return;
 993   }
 994   JavaThread* thread = JavaThread::current();
 995   EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_UNLOAD,
 996                  ("[%s] method compile unload event triggered",
 997                   JvmtiTrace::safe_get_thread_name(thread)));
 998 
 999   // post the event for each environment that has this event enabled.
1000   JvmtiEnvIterator it;
1001   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1002     if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_UNLOAD)) {
1003       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1004         continue;
1005       }
1006       EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_UNLOAD,
1007                 ("[%s] class compile method unload event sent jmethodID " PTR_FORMAT,
1008                  JvmtiTrace::safe_get_thread_name(thread), p2i(method)));
1009 
1010       ResourceMark rm(thread);
1011 
1012       JvmtiEventMark jem(thread);
1013       JvmtiJavaThreadEventTransition jet(thread);
1014       jvmtiEventCompiledMethodUnload callback = env->callbacks()->CompiledMethodUnload;
1015       if (callback != NULL) {
1016         (*callback)(env->jvmti_external(), method, code_begin);
1017       }
1018     }
1019   }
1020 }
1021 
1022 ///////////////////////////////////////////////////////////////
1023 //
1024 // JvmtiExport
1025 //
1026 
1027 void JvmtiExport::post_raw_breakpoint(JavaThread *thread, Method* method, address location) {
1028   HandleMark hm(thread);
1029   methodHandle mh(thread, method);
1030 
1031   JvmtiThreadState *state = thread->jvmti_thread_state();
1032   if (state == NULL) {
1033     return;
1034   }
1035   EVT_TRIG_TRACE(JVMTI_EVENT_BREAKPOINT, ("[%s] Trg Breakpoint triggered",
1036                       JvmtiTrace::safe_get_thread_name(thread)));
1037   JvmtiEnvThreadStateIterator it(state);
1038   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1039     ets->compare_and_set_current_location(mh(), location, JVMTI_EVENT_BREAKPOINT);
1040     if (!ets->breakpoint_posted() && ets->is_enabled(JVMTI_EVENT_BREAKPOINT)) {
1041       ThreadState old_os_state = thread->osthread()->get_state();
1042       thread->osthread()->set_state(BREAKPOINTED);
1043       EVT_TRACE(JVMTI_EVENT_BREAKPOINT, ("[%s] Evt Breakpoint sent %s.%s @ " INTX_FORMAT,
1044                      JvmtiTrace::safe_get_thread_name(thread),
1045                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1046                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1047                      location - mh()->code_base() ));
1048 
1049       JvmtiEnv *env = ets->get_env();
1050       JvmtiLocationEventMark jem(thread, mh, location);
1051       JvmtiJavaThreadEventTransition jet(thread);
1052       jvmtiEventBreakpoint callback = env->callbacks()->Breakpoint;
1053       if (callback != NULL) {
1054         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1055                     jem.jni_methodID(), jem.location());
1056       }
1057 
1058       ets->set_breakpoint_posted();
1059       thread->osthread()->set_state(old_os_state);
1060     }
1061   }
1062 }
1063 
1064 //////////////////////////////////////////////////////////////////////////////
1065 
1066 bool              JvmtiExport::_can_get_source_debug_extension            = false;
1067 bool              JvmtiExport::_can_maintain_original_method_order        = false;
1068 bool              JvmtiExport::_can_post_interpreter_events               = false;
1069 bool              JvmtiExport::_can_post_on_exceptions                    = false;
1070 bool              JvmtiExport::_can_post_breakpoint                       = false;
1071 bool              JvmtiExport::_can_post_field_access                     = false;
1072 bool              JvmtiExport::_can_post_field_modification               = false;
1073 bool              JvmtiExport::_can_post_method_entry                     = false;
1074 bool              JvmtiExport::_can_post_method_exit                      = false;
1075 bool              JvmtiExport::_can_pop_frame                             = false;
1076 bool              JvmtiExport::_can_force_early_return                    = false;
1077 
1078 bool              JvmtiExport::_early_vmstart_recorded                    = false;
1079 
1080 bool              JvmtiExport::_should_post_single_step                   = false;
1081 bool              JvmtiExport::_should_post_field_access                  = false;
1082 bool              JvmtiExport::_should_post_field_modification            = false;
1083 bool              JvmtiExport::_should_post_class_load                    = false;
1084 bool              JvmtiExport::_should_post_class_prepare                 = false;
1085 bool              JvmtiExport::_should_post_class_unload                  = false;
1086 bool              JvmtiExport::_should_post_thread_life                   = false;
1087 bool              JvmtiExport::_should_clean_up_heap_objects              = false;
1088 bool              JvmtiExport::_should_post_native_method_bind            = false;
1089 bool              JvmtiExport::_should_post_dynamic_code_generated        = false;
1090 bool              JvmtiExport::_should_post_data_dump                     = false;
1091 bool              JvmtiExport::_should_post_compiled_method_load          = false;
1092 bool              JvmtiExport::_should_post_compiled_method_unload        = false;
1093 bool              JvmtiExport::_should_post_monitor_contended_enter       = false;
1094 bool              JvmtiExport::_should_post_monitor_contended_entered     = false;
1095 bool              JvmtiExport::_should_post_monitor_wait                  = false;
1096 bool              JvmtiExport::_should_post_monitor_waited                = false;
1097 bool              JvmtiExport::_should_post_garbage_collection_start      = false;
1098 bool              JvmtiExport::_should_post_garbage_collection_finish     = false;
1099 bool              JvmtiExport::_should_post_object_free                   = false;
1100 bool              JvmtiExport::_should_post_resource_exhausted            = false;
1101 bool              JvmtiExport::_should_post_vm_object_alloc               = false;
1102 bool              JvmtiExport::_should_post_on_exceptions                 = false;
1103 
1104 ////////////////////////////////////////////////////////////////////////////////////////////////
1105 
1106 
1107 //
1108 // JVMTI single step management
1109 //
1110 void JvmtiExport::at_single_stepping_point(JavaThread *thread, Method* method, address location) {
1111   assert(JvmtiExport::should_post_single_step(), "must be single stepping");
1112 
1113   HandleMark hm(thread);
1114   methodHandle mh(thread, method);
1115 
1116   // update information about current location and post a step event
1117   JvmtiThreadState *state = thread->jvmti_thread_state();
1118   if (state == NULL) {
1119     return;
1120   }
1121   EVT_TRIG_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Trg Single Step triggered",
1122                       JvmtiTrace::safe_get_thread_name(thread)));
1123   if (!state->hide_single_stepping()) {
1124     if (state->is_pending_step_for_popframe()) {
1125       state->process_pending_step_for_popframe();
1126     }
1127     if (state->is_pending_step_for_earlyret()) {
1128       state->process_pending_step_for_earlyret();
1129     }
1130     JvmtiExport::post_single_step(thread, mh(), location);
1131   }
1132 }
1133 
1134 
1135 void JvmtiExport::expose_single_stepping(JavaThread *thread) {
1136   JvmtiThreadState *state = thread->jvmti_thread_state();
1137   if (state != NULL) {
1138     state->clear_hide_single_stepping();
1139   }
1140 }
1141 
1142 
1143 bool JvmtiExport::hide_single_stepping(JavaThread *thread) {
1144   JvmtiThreadState *state = thread->jvmti_thread_state();
1145   if (state != NULL && state->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1146     state->set_hide_single_stepping();
1147     return true;
1148   } else {
1149     return false;
1150   }
1151 }
1152 
1153 void JvmtiExport::post_class_load(JavaThread *thread, Klass* klass) {
1154   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1155     return;
1156   }
1157   HandleMark hm(thread);

1158 
1159   EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Trg Class Load triggered",
1160                       JvmtiTrace::safe_get_thread_name(thread)));
1161   JvmtiThreadState* state = thread->jvmti_thread_state();
1162   if (state == NULL) {
1163     return;
1164   }
1165   JvmtiEnvThreadStateIterator it(state);
1166   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1167     if (ets->is_enabled(JVMTI_EVENT_CLASS_LOAD)) {
1168       JvmtiEnv *env = ets->get_env();
1169       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1170         continue;
1171       }
1172       EVT_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Evt Class Load sent %s",
1173                                          JvmtiTrace::safe_get_thread_name(thread),
1174                                          klass==NULL? "NULL" : klass->external_name() ));
1175       JvmtiClassEventMark jem(thread, klass);
1176       JvmtiJavaThreadEventTransition jet(thread);
1177       jvmtiEventClassLoad callback = env->callbacks()->ClassLoad;
1178       if (callback != NULL) {
1179         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1180       }
1181     }
1182   }
1183 }
1184 
1185 
1186 void JvmtiExport::post_class_prepare(JavaThread *thread, Klass* klass) {
1187   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1188     return;
1189   }
1190   HandleMark hm(thread);

1191 
1192   EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Trg Class Prepare triggered",
1193                       JvmtiTrace::safe_get_thread_name(thread)));
1194   JvmtiThreadState* state = thread->jvmti_thread_state();
1195   if (state == NULL) {
1196     return;
1197   }
1198   JvmtiEnvThreadStateIterator it(state);
1199   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1200     if (ets->is_enabled(JVMTI_EVENT_CLASS_PREPARE)) {
1201       JvmtiEnv *env = ets->get_env();
1202       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1203         continue;
1204       }
1205       EVT_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Evt Class Prepare sent %s",
1206                                             JvmtiTrace::safe_get_thread_name(thread),
1207                                             klass==NULL? "NULL" : klass->external_name() ));
1208       JvmtiClassEventMark jem(thread, klass);
1209       JvmtiJavaThreadEventTransition jet(thread);
1210       jvmtiEventClassPrepare callback = env->callbacks()->ClassPrepare;
1211       if (callback != NULL) {
1212         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1213       }
1214     }
1215   }
1216 }
1217 
1218 void JvmtiExport::post_class_unload(Klass* klass) {
1219   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1220     return;
1221   }
1222   Thread *thread = Thread::current();
1223   HandleMark hm(thread);

1224 
1225   EVT_TRIG_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Trg Class Unload triggered" ));
1226   if (JvmtiEventController::is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1227     assert(thread->is_VM_thread(), "wrong thread");
1228 
1229     // get JavaThread for whom we are proxy
1230     Thread *calling_thread = ((VMThread *)thread)->vm_operation()->calling_thread();
1231     if (!calling_thread->is_Java_thread()) {
1232       // cannot post an event to a non-JavaThread
1233       return;
1234     }
1235     JavaThread *real_thread = (JavaThread *)calling_thread;
1236 
1237     JvmtiEnvIterator it;
1238     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1239       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1240         continue;
1241       }
1242       if (env->is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1243         EVT_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Evt Class Unload sent %s",
1244                   klass==NULL? "NULL" : klass->external_name() ));
1245 
1246         // do everything manually, since this is a proxy - needs special care
1247         JNIEnv* jni_env = real_thread->jni_environment();
1248         jthread jt = (jthread)JNIHandles::make_local(real_thread, real_thread->threadObj());
1249         jclass jk = (jclass)JNIHandles::make_local(real_thread, klass->java_mirror());
1250 
1251         // Before we call the JVMTI agent, we have to set the state in the
1252         // thread for which we are proxying.
1253         JavaThreadState prev_state = real_thread->thread_state();
1254         assert(((Thread *)real_thread)->is_ConcurrentGC_thread() ||
1255                (real_thread->is_Java_thread() && prev_state == _thread_blocked),
1256                "should be ConcurrentGCThread or JavaThread at safepoint");
1257         real_thread->set_thread_state(_thread_in_native);
1258 
1259         jvmtiExtensionEvent callback = env->ext_callbacks()->ClassUnload;
1260         if (callback != NULL) {
1261           (*callback)(env->jvmti_external(), jni_env, jt, jk);
1262         }
1263 
1264         assert(real_thread->thread_state() == _thread_in_native,
1265                "JavaThread should be in native");
1266         real_thread->set_thread_state(prev_state);
1267 
1268         JNIHandles::destroy_local(jk);
1269         JNIHandles::destroy_local(jt);
1270       }
1271     }
1272   }
1273 }
1274 
1275 
1276 void JvmtiExport::post_thread_start(JavaThread *thread) {
1277   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1278     return;
1279   }
1280   assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
1281 
1282   EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Trg Thread Start event triggered",
1283                       JvmtiTrace::safe_get_thread_name(thread)));
1284 
1285   // do JVMTI thread initialization (if needed)
1286   JvmtiEventController::thread_started(thread);
1287 
1288   // Do not post thread start event for hidden java thread.
1289   if (JvmtiEventController::is_enabled(JVMTI_EVENT_THREAD_START) &&
1290       !thread->is_hidden_from_external_view()) {
1291     JvmtiEnvIterator it;
1292     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1293       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1294         continue;
1295       }
1296       if (env->is_enabled(JVMTI_EVENT_THREAD_START)) {
1297         EVT_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Evt Thread Start event sent",
1298                      JvmtiTrace::safe_get_thread_name(thread) ));
1299 
1300         JvmtiThreadEventMark jem(thread);
1301         JvmtiJavaThreadEventTransition jet(thread);
1302         jvmtiEventThreadStart callback = env->callbacks()->ThreadStart;
1303         if (callback != NULL) {
1304           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1305         }
1306       }
1307     }
1308   }
1309 }
1310 
1311 
1312 void JvmtiExport::post_thread_end(JavaThread *thread) {
1313   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1314     return;
1315   }
1316   EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Trg Thread End event triggered",
1317                       JvmtiTrace::safe_get_thread_name(thread)));
1318 
1319   JvmtiThreadState *state = thread->jvmti_thread_state();
1320   if (state == NULL) {
1321     return;
1322   }
1323 
1324   // Do not post thread end event for hidden java thread.
1325   if (state->is_enabled(JVMTI_EVENT_THREAD_END) &&
1326       !thread->is_hidden_from_external_view()) {
1327 
1328     JvmtiEnvThreadStateIterator it(state);
1329     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1330       if (ets->is_enabled(JVMTI_EVENT_THREAD_END)) {
1331         JvmtiEnv *env = ets->get_env();
1332         if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1333           continue;
1334         }
1335         EVT_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Evt Thread End event sent",
1336                      JvmtiTrace::safe_get_thread_name(thread) ));
1337 
1338         JvmtiThreadEventMark jem(thread);
1339         JvmtiJavaThreadEventTransition jet(thread);
1340         jvmtiEventThreadEnd callback = env->callbacks()->ThreadEnd;
1341         if (callback != NULL) {
1342           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1343         }
1344       }
1345     }
1346   }
1347 }
1348 
1349 void JvmtiExport::post_object_free(JvmtiEnv* env, jlong tag) {
1350   assert(SafepointSynchronize::is_at_safepoint(), "must be executed at safepoint");
1351   assert(env->is_enabled(JVMTI_EVENT_OBJECT_FREE), "checking");
1352 
1353   EVT_TRIG_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Trg Object Free triggered" ));
1354   EVT_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Evt Object Free sent"));
1355 
1356   jvmtiEventObjectFree callback = env->callbacks()->ObjectFree;
1357   if (callback != NULL) {
1358     (*callback)(env->jvmti_external(), tag);
1359   }
1360 }
1361 
1362 void JvmtiExport::post_resource_exhausted(jint resource_exhausted_flags, const char* description) {
1363   EVT_TRIG_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Trg resource exhausted event triggered" ));
1364 
1365   JvmtiEnvIterator it;
1366   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1367     if (env->is_enabled(JVMTI_EVENT_RESOURCE_EXHAUSTED)) {
1368       EVT_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Evt resource exhausted event sent" ));
1369 
1370       JavaThread *thread  = JavaThread::current();
1371       JvmtiThreadEventMark jem(thread);
1372       JvmtiJavaThreadEventTransition jet(thread);
1373       jvmtiEventResourceExhausted callback = env->callbacks()->ResourceExhausted;
1374       if (callback != NULL) {
1375         (*callback)(env->jvmti_external(), jem.jni_env(),
1376                     resource_exhausted_flags, NULL, description);
1377       }
1378     }
1379   }
1380 }
1381 
1382 void JvmtiExport::post_method_entry(JavaThread *thread, Method* method, frame current_frame) {
1383   HandleMark hm(thread);
1384   methodHandle mh(thread, method);
1385 
1386   EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Trg Method Entry triggered %s.%s",
1387                      JvmtiTrace::safe_get_thread_name(thread),
1388                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1389                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1390 
1391   JvmtiThreadState* state = thread->jvmti_thread_state();
1392   if (state == NULL || !state->is_interp_only_mode()) {
1393     // for any thread that actually wants method entry, interp_only_mode is set
1394     return;
1395   }
1396 
1397   state->incr_cur_stack_depth();
1398 
1399   if (state->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1400     JvmtiEnvThreadStateIterator it(state);
1401     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1402       if (ets->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1403         EVT_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Evt Method Entry sent %s.%s",
1404                                              JvmtiTrace::safe_get_thread_name(thread),
1405                                              (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1406                                              (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1407 
1408         JvmtiEnv *env = ets->get_env();
1409         JvmtiMethodEventMark jem(thread, mh);
1410         JvmtiJavaThreadEventTransition jet(thread);
1411         jvmtiEventMethodEntry callback = env->callbacks()->MethodEntry;
1412         if (callback != NULL) {
1413           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_methodID());
1414         }
1415       }
1416     }
1417   }
1418 }
1419 
1420 void JvmtiExport::post_method_exit(JavaThread *thread, Method* method, frame current_frame) {
1421   HandleMark hm(thread);
1422   methodHandle mh(thread, method);
1423 
1424   EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Trg Method Exit triggered %s.%s",
1425                      JvmtiTrace::safe_get_thread_name(thread),
1426                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1427                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1428 
1429   JvmtiThreadState *state = thread->jvmti_thread_state();
1430   if (state == NULL || !state->is_interp_only_mode()) {
1431     // for any thread that actually wants method exit, interp_only_mode is set
1432     return;
1433   }
1434 
1435   // return a flag when a method terminates by throwing an exception
1436   // i.e. if an exception is thrown and it's not caught by the current method
1437   bool exception_exit = state->is_exception_detected() && !state->is_exception_caught();
1438 
1439 
1440   if (state->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1441     Handle result;
1442     jvalue value;
1443     value.j = 0L;
1444 
1445     // if the method hasn't been popped because of an exception then we populate
1446     // the return_value parameter for the callback. At this point we only have
1447     // the address of a "raw result" and we just call into the interpreter to
1448     // convert this into a jvalue.
1449     if (!exception_exit) {
1450       oop oop_result;
1451       BasicType type = current_frame.interpreter_frame_result(&oop_result, &value);
1452       if (type == T_OBJECT || type == T_ARRAY) {
1453         result = Handle(thread, oop_result);
1454       }
1455     }
1456 
1457     JvmtiEnvThreadStateIterator it(state);
1458     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1459       if (ets->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1460         EVT_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Evt Method Exit sent %s.%s",
1461                                             JvmtiTrace::safe_get_thread_name(thread),
1462                                             (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1463                                             (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1464 
1465         JvmtiEnv *env = ets->get_env();
1466         JvmtiMethodEventMark jem(thread, mh);
1467         if (result.not_null()) {
1468           value.l = JNIHandles::make_local(thread, result());
1469         }
1470         JvmtiJavaThreadEventTransition jet(thread);
1471         jvmtiEventMethodExit callback = env->callbacks()->MethodExit;
1472         if (callback != NULL) {
1473           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1474                       jem.jni_methodID(), exception_exit,  value);
1475         }
1476       }
1477     }
1478   }
1479 
1480   if (state->is_enabled(JVMTI_EVENT_FRAME_POP)) {
1481     JvmtiEnvThreadStateIterator it(state);
1482     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1483       int cur_frame_number = state->cur_stack_depth();
1484 
1485       if (ets->is_frame_pop(cur_frame_number)) {
1486         // we have a NotifyFramePop entry for this frame.
1487         // now check that this env/thread wants this event
1488         if (ets->is_enabled(JVMTI_EVENT_FRAME_POP)) {
1489           EVT_TRACE(JVMTI_EVENT_FRAME_POP, ("[%s] Evt Frame Pop sent %s.%s",
1490                                             JvmtiTrace::safe_get_thread_name(thread),
1491                                             (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1492                                             (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1493 
1494           // we also need to issue a frame pop event for this frame
1495           JvmtiEnv *env = ets->get_env();
1496           JvmtiMethodEventMark jem(thread, mh);
1497           JvmtiJavaThreadEventTransition jet(thread);
1498           jvmtiEventFramePop callback = env->callbacks()->FramePop;
1499           if (callback != NULL) {
1500             (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1501                         jem.jni_methodID(), exception_exit);
1502           }
1503         }
1504         // remove the frame's entry
1505         ets->clear_frame_pop(cur_frame_number);
1506       }
1507     }
1508   }
1509 
1510   state->decr_cur_stack_depth();
1511 }
1512 
1513 
1514 // Todo: inline this for optimization
1515 void JvmtiExport::post_single_step(JavaThread *thread, Method* method, address location) {
1516   HandleMark hm(thread);
1517   methodHandle mh(thread, method);
1518 
1519   JvmtiThreadState *state = thread->jvmti_thread_state();
1520   if (state == NULL) {
1521     return;
1522   }
1523   JvmtiEnvThreadStateIterator it(state);
1524   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1525     ets->compare_and_set_current_location(mh(), location, JVMTI_EVENT_SINGLE_STEP);
1526     if (!ets->single_stepping_posted() && ets->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1527       EVT_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Evt Single Step sent %s.%s @ " INTX_FORMAT,
1528                     JvmtiTrace::safe_get_thread_name(thread),
1529                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1530                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1531                     location - mh()->code_base() ));
1532 
1533       JvmtiEnv *env = ets->get_env();
1534       JvmtiLocationEventMark jem(thread, mh, location);
1535       JvmtiJavaThreadEventTransition jet(thread);
1536       jvmtiEventSingleStep callback = env->callbacks()->SingleStep;
1537       if (callback != NULL) {
1538         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1539                     jem.jni_methodID(), jem.location());
1540       }
1541 
1542       ets->set_single_stepping_posted();
1543     }
1544   }
1545 }
1546 
1547 void JvmtiExport::post_exception_throw(JavaThread *thread, Method* method, address location, oop exception) {
1548   HandleMark hm(thread);
1549   methodHandle mh(thread, method);
1550   Handle exception_handle(thread, exception);
1551 
1552   JvmtiThreadState *state = thread->jvmti_thread_state();
1553   if (state == NULL) {
1554     return;
1555   }
1556 
1557   EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION, ("[%s] Trg Exception thrown triggered",
1558                       JvmtiTrace::safe_get_thread_name(thread)));
1559   if (!state->is_exception_detected()) {
1560     state->set_exception_detected();
1561     JvmtiEnvThreadStateIterator it(state);
1562     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1563       if (ets->is_enabled(JVMTI_EVENT_EXCEPTION) && (exception != NULL)) {
1564 
1565         EVT_TRACE(JVMTI_EVENT_EXCEPTION,
1566                      ("[%s] Evt Exception thrown sent %s.%s @ " INTX_FORMAT,
1567                       JvmtiTrace::safe_get_thread_name(thread),
1568                       (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1569                       (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1570                       location - mh()->code_base() ));
1571 
1572         JvmtiEnv *env = ets->get_env();
1573         JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1574 
1575         // It's okay to clear these exceptions here because we duplicate
1576         // this lookup in InterpreterRuntime::exception_handler_for_exception.
1577         EXCEPTION_MARK;
1578 
1579         bool should_repeat;
1580         vframeStream st(thread);
1581         assert(!st.at_end(), "cannot be at end");
1582         Method* current_method = NULL;
1583         // A GC may occur during the Method::fast_exception_handler_bci_for()
1584         // call below if it needs to load the constraint class. Using a
1585         // methodHandle to keep the 'current_method' from being deallocated
1586         // if GC happens.
1587         methodHandle current_mh = methodHandle(thread, current_method);
1588         int current_bci = -1;
1589         do {
1590           current_method = st.method();
1591           current_mh = methodHandle(thread, current_method);
1592           current_bci = st.bci();
1593           do {
1594             should_repeat = false;
1595             Klass* eh_klass = exception_handle()->klass();
1596             current_bci = Method::fast_exception_handler_bci_for(
1597               current_mh, eh_klass, current_bci, THREAD);
1598             if (HAS_PENDING_EXCEPTION) {
1599               exception_handle = Handle(thread, PENDING_EXCEPTION);
1600               CLEAR_PENDING_EXCEPTION;
1601               should_repeat = true;
1602             }
1603           } while (should_repeat && (current_bci != -1));
1604           st.next();
1605         } while ((current_bci < 0) && (!st.at_end()));
1606 
1607         jmethodID catch_jmethodID;
1608         if (current_bci < 0) {
1609           catch_jmethodID = 0;
1610           current_bci = 0;
1611         } else {
1612           catch_jmethodID = jem.to_jmethodID(current_mh);
1613         }
1614 
1615         JvmtiJavaThreadEventTransition jet(thread);
1616         jvmtiEventException callback = env->callbacks()->Exception;
1617         if (callback != NULL) {
1618           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1619                       jem.jni_methodID(), jem.location(),
1620                       jem.exception(),
1621                       catch_jmethodID, current_bci);
1622         }
1623       }
1624     }
1625   }
1626 
1627   // frames may get popped because of this throw, be safe - invalidate cached depth
1628   state->invalidate_cur_stack_depth();
1629 }
1630 
1631 
1632 void JvmtiExport::notice_unwind_due_to_exception(JavaThread *thread, Method* method, address location, oop exception, bool in_handler_frame) {
1633   HandleMark hm(thread);
1634   methodHandle mh(thread, method);
1635   Handle exception_handle(thread, exception);
1636 
1637   JvmtiThreadState *state = thread->jvmti_thread_state();
1638   if (state == NULL) {
1639     return;
1640   }
1641   EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1642                     ("[%s] Trg unwind_due_to_exception triggered %s.%s @ %s" INTX_FORMAT " - %s",
1643                      JvmtiTrace::safe_get_thread_name(thread),
1644                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1645                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1646                      location==0? "no location:" : "",
1647                      location==0? 0 : location - mh()->code_base(),
1648                      in_handler_frame? "in handler frame" : "not handler frame" ));
1649 
1650   if (state->is_exception_detected()) {
1651 
1652     state->invalidate_cur_stack_depth();
1653     if (!in_handler_frame) {
1654       // Not in exception handler.
1655       if(state->is_interp_only_mode()) {
1656         // method exit and frame pop events are posted only in interp mode.
1657         // When these events are enabled code should be in running in interp mode.
1658         JvmtiExport::post_method_exit(thread, method, thread->last_frame());
1659         // The cached cur_stack_depth might have changed from the
1660         // operations of frame pop or method exit. We are not 100% sure
1661         // the cached cur_stack_depth is still valid depth so invalidate
1662         // it.
1663         state->invalidate_cur_stack_depth();
1664       }
1665     } else {
1666       // In exception handler frame. Report exception catch.
1667       assert(location != NULL, "must be a known location");
1668       // Update cur_stack_depth - the frames above the current frame
1669       // have been unwound due to this exception:
1670       assert(!state->is_exception_caught(), "exception must not be caught yet.");
1671       state->set_exception_caught();
1672 
1673       JvmtiEnvThreadStateIterator it(state);
1674       for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1675         if (ets->is_enabled(JVMTI_EVENT_EXCEPTION_CATCH) && (exception_handle() != NULL)) {
1676           EVT_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1677                      ("[%s] Evt ExceptionCatch sent %s.%s @ " INTX_FORMAT,
1678                       JvmtiTrace::safe_get_thread_name(thread),
1679                       (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1680                       (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1681                       location - mh()->code_base() ));
1682 
1683           JvmtiEnv *env = ets->get_env();
1684           JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1685           JvmtiJavaThreadEventTransition jet(thread);
1686           jvmtiEventExceptionCatch callback = env->callbacks()->ExceptionCatch;
1687           if (callback != NULL) {
1688             (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1689                       jem.jni_methodID(), jem.location(),
1690                       jem.exception());
1691           }
1692         }
1693       }
1694     }
1695   }
1696 }
1697 
1698 oop JvmtiExport::jni_GetField_probe(JavaThread *thread, jobject jobj, oop obj,
1699                                     Klass* klass, jfieldID fieldID, bool is_static) {
1700   if (*((int *)get_field_access_count_addr()) > 0 && thread->has_last_Java_frame()) {
1701     // At least one field access watch is set so we have more work
1702     // to do. This wrapper is used by entry points that allow us
1703     // to create handles in post_field_access_by_jni().
1704     post_field_access_by_jni(thread, obj, klass, fieldID, is_static);
1705     // event posting can block so refetch oop if we were passed a jobj
1706     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1707   }
1708   return obj;
1709 }
1710 
1711 oop JvmtiExport::jni_GetField_probe_nh(JavaThread *thread, jobject jobj, oop obj,
1712                                        Klass* klass, jfieldID fieldID, bool is_static) {
1713   if (*((int *)get_field_access_count_addr()) > 0 && thread->has_last_Java_frame()) {
1714     // At least one field access watch is set so we have more work
1715     // to do. This wrapper is used by "quick" entry points that don't
1716     // allow us to create handles in post_field_access_by_jni(). We
1717     // override that with a ResetNoHandleMark.
1718     ResetNoHandleMark rnhm;
1719     post_field_access_by_jni(thread, obj, klass, fieldID, is_static);
1720     // event posting can block so refetch oop if we were passed a jobj
1721     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1722   }
1723   return obj;
1724 }
1725 
1726 void JvmtiExport::post_field_access_by_jni(JavaThread *thread, oop obj,
1727                                            Klass* klass, jfieldID fieldID, bool is_static) {
1728   // We must be called with a Java context in order to provide reasonable
1729   // values for the klazz, method, and location fields. The callers of this
1730   // function don't make the call unless there is a Java context.
1731   assert(thread->has_last_Java_frame(), "must be called with a Java context");
1732 
1733   ResourceMark rm;
1734   fieldDescriptor fd;
1735   // if get_field_descriptor finds fieldID to be invalid, then we just bail
1736   bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1737   assert(valid_fieldID == true,"post_field_access_by_jni called with invalid fieldID");
1738   if (!valid_fieldID) return;
1739   // field accesses are not watched so bail
1740   if (!fd.is_field_access_watched()) return;
1741 
1742   HandleMark hm(thread);

1743   Handle h_obj;
1744   if (!is_static) {
1745     // non-static field accessors have an object, but we need a handle
1746     assert(obj != NULL, "non-static needs an object");
1747     h_obj = Handle(thread, obj);
1748   }
1749   post_field_access(thread,
1750                     thread->last_frame().interpreter_frame_method(),
1751                     thread->last_frame().interpreter_frame_bcp(),
1752                     klass, h_obj, fieldID);
1753 }
1754 
1755 void JvmtiExport::post_field_access(JavaThread *thread, Method* method,
1756   address location, Klass* field_klass, Handle object, jfieldID field) {
1757 
1758   HandleMark hm(thread);
1759   methodHandle mh(thread, method);
1760 
1761   JvmtiThreadState *state = thread->jvmti_thread_state();
1762   if (state == NULL) {
1763     return;
1764   }
1765   EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Trg Field Access event triggered",
1766                       JvmtiTrace::safe_get_thread_name(thread)));
1767   JvmtiEnvThreadStateIterator it(state);
1768   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1769     if (ets->is_enabled(JVMTI_EVENT_FIELD_ACCESS)) {
1770       EVT_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Evt Field Access event sent %s.%s @ " INTX_FORMAT,
1771                      JvmtiTrace::safe_get_thread_name(thread),
1772                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1773                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1774                      location - mh()->code_base() ));
1775 
1776       JvmtiEnv *env = ets->get_env();
1777       JvmtiLocationEventMark jem(thread, mh, location);
1778       jclass field_jclass = jem.to_jclass(field_klass);
1779       jobject field_jobject = jem.to_jobject(object());
1780       JvmtiJavaThreadEventTransition jet(thread);
1781       jvmtiEventFieldAccess callback = env->callbacks()->FieldAccess;
1782       if (callback != NULL) {
1783         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1784                     jem.jni_methodID(), jem.location(),
1785                     field_jclass, field_jobject, field);
1786       }
1787     }
1788   }
1789 }
1790 
1791 oop JvmtiExport::jni_SetField_probe(JavaThread *thread, jobject jobj, oop obj,
1792                                     Klass* klass, jfieldID fieldID, bool is_static,
1793                                     char sig_type, jvalue *value) {
1794   if (*((int *)get_field_modification_count_addr()) > 0 && thread->has_last_Java_frame()) {
1795     // At least one field modification watch is set so we have more work
1796     // to do. This wrapper is used by entry points that allow us
1797     // to create handles in post_field_modification_by_jni().
1798     post_field_modification_by_jni(thread, obj, klass, fieldID, is_static, sig_type, value);
1799     // event posting can block so refetch oop if we were passed a jobj
1800     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1801   }
1802   return obj;
1803 }
1804 
1805 oop JvmtiExport::jni_SetField_probe_nh(JavaThread *thread, jobject jobj, oop obj,
1806                                        Klass* klass, jfieldID fieldID, bool is_static,
1807                                        char sig_type, jvalue *value) {
1808   if (*((int *)get_field_modification_count_addr()) > 0 && thread->has_last_Java_frame()) {
1809     // At least one field modification watch is set so we have more work
1810     // to do. This wrapper is used by "quick" entry points that don't
1811     // allow us to create handles in post_field_modification_by_jni(). We
1812     // override that with a ResetNoHandleMark.
1813     ResetNoHandleMark rnhm;
1814     post_field_modification_by_jni(thread, obj, klass, fieldID, is_static, sig_type, value);
1815     // event posting can block so refetch oop if we were passed a jobj
1816     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1817   }
1818   return obj;
1819 }
1820 
1821 void JvmtiExport::post_field_modification_by_jni(JavaThread *thread, oop obj,
1822                                                  Klass* klass, jfieldID fieldID, bool is_static,
1823                                                  char sig_type, jvalue *value) {
1824   // We must be called with a Java context in order to provide reasonable
1825   // values for the klazz, method, and location fields. The callers of this
1826   // function don't make the call unless there is a Java context.
1827   assert(thread->has_last_Java_frame(), "must be called with Java context");
1828 
1829   ResourceMark rm;
1830   fieldDescriptor fd;
1831   // if get_field_descriptor finds fieldID to be invalid, then we just bail
1832   bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1833   assert(valid_fieldID == true,"post_field_modification_by_jni called with invalid fieldID");
1834   if (!valid_fieldID) return;
1835   // field modifications are not watched so bail
1836   if (!fd.is_field_modification_watched()) return;
1837 
1838   HandleMark hm(thread);
1839 
1840   Handle h_obj;
1841   if (!is_static) {
1842     // non-static field accessors have an object, but we need a handle
1843     assert(obj != NULL, "non-static needs an object");
1844     h_obj = Handle(thread, obj);
1845   }

1846   post_field_modification(thread,
1847                           thread->last_frame().interpreter_frame_method(),
1848                           thread->last_frame().interpreter_frame_bcp(),
1849                           klass, h_obj, fieldID, sig_type, value);
1850 }
1851 
1852 void JvmtiExport::post_raw_field_modification(JavaThread *thread, Method* method,
1853   address location, Klass* field_klass, Handle object, jfieldID field,
1854   char sig_type, jvalue *value) {
1855 
1856   if (sig_type == 'I' || sig_type == 'Z' || sig_type == 'B' || sig_type == 'C' || sig_type == 'S') {
1857     // 'I' instructions are used for byte, char, short and int.
1858     // determine which it really is, and convert
1859     fieldDescriptor fd;
1860     bool found = JvmtiEnv::get_field_descriptor(field_klass, field, &fd);
1861     // should be found (if not, leave as is)
1862     if (found) {
1863       jint ival = value->i;
1864       // convert value from int to appropriate type
1865       switch (fd.field_type()) {
1866       case T_BOOLEAN:
1867         sig_type = 'Z';
1868         value->i = 0; // clear it
1869         value->z = (jboolean)ival;
1870         break;
1871       case T_BYTE:
1872         sig_type = 'B';
1873         value->i = 0; // clear it
1874         value->b = (jbyte)ival;
1875         break;
1876       case T_CHAR:
1877         sig_type = 'C';
1878         value->i = 0; // clear it
1879         value->c = (jchar)ival;
1880         break;
1881       case T_SHORT:
1882         sig_type = 'S';
1883         value->i = 0; // clear it
1884         value->s = (jshort)ival;
1885         break;
1886       case T_INT:
1887         // nothing to do
1888         break;
1889       default:
1890         // this is an integer instruction, should be one of above
1891         ShouldNotReachHere();
1892         break;
1893       }
1894     }
1895   }
1896 
1897   assert(sig_type != '[', "array should have sig_type == 'L'");
1898   bool handle_created = false;
1899 
1900   // convert oop to JNI handle.
1901   if (sig_type == 'L') {
1902     handle_created = true;
1903     value->l = (jobject)JNIHandles::make_local(thread, (oop)value->l);
1904   }
1905 
1906   post_field_modification(thread, method, location, field_klass, object, field, sig_type, value);
1907 
1908   // Destroy the JNI handle allocated above.
1909   if (handle_created) {
1910     JNIHandles::destroy_local(value->l);
1911   }
1912 }
1913 
1914 void JvmtiExport::post_field_modification(JavaThread *thread, Method* method,
1915   address location, Klass* field_klass, Handle object, jfieldID field,
1916   char sig_type, jvalue *value_ptr) {
1917 
1918   HandleMark hm(thread);
1919   methodHandle mh(thread, method);
1920 
1921   JvmtiThreadState *state = thread->jvmti_thread_state();
1922   if (state == NULL) {
1923     return;
1924   }
1925   EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
1926                      ("[%s] Trg Field Modification event triggered",
1927                       JvmtiTrace::safe_get_thread_name(thread)));
1928 
1929   JvmtiEnvThreadStateIterator it(state);
1930   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1931     if (ets->is_enabled(JVMTI_EVENT_FIELD_MODIFICATION)) {
1932       EVT_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
1933                    ("[%s] Evt Field Modification event sent %s.%s @ " INTX_FORMAT,
1934                     JvmtiTrace::safe_get_thread_name(thread),
1935                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1936                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1937                     location - mh()->code_base() ));
1938 
1939       JvmtiEnv *env = ets->get_env();
1940       JvmtiLocationEventMark jem(thread, mh, location);
1941       jclass field_jclass = jem.to_jclass(field_klass);
1942       jobject field_jobject = jem.to_jobject(object());
1943       JvmtiJavaThreadEventTransition jet(thread);
1944       jvmtiEventFieldModification callback = env->callbacks()->FieldModification;
1945       if (callback != NULL) {
1946         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1947                     jem.jni_methodID(), jem.location(),
1948                     field_jclass, field_jobject, field, sig_type, *value_ptr);
1949       }
1950     }
1951   }
1952 }
1953 
1954 void JvmtiExport::post_native_method_bind(Method* method, address* function_ptr) {
1955   JavaThread* thread = JavaThread::current();
1956   assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
1957 
1958   HandleMark hm(thread);
1959   methodHandle mh(thread, method);
1960 
1961   EVT_TRIG_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Trg Native Method Bind event triggered",
1962                       JvmtiTrace::safe_get_thread_name(thread)));
1963 
1964   if (JvmtiEventController::is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
1965     JvmtiEnvIterator it;
1966     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1967       if (env->is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
1968         EVT_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Evt Native Method Bind event sent",
1969                      JvmtiTrace::safe_get_thread_name(thread) ));
1970 
1971         JvmtiMethodEventMark jem(thread, mh);
1972         JvmtiJavaThreadEventTransition jet(thread);
1973         JNIEnv* jni_env = (env->phase() == JVMTI_PHASE_PRIMORDIAL) ? NULL : jem.jni_env();
1974         jvmtiEventNativeMethodBind callback = env->callbacks()->NativeMethodBind;
1975         if (callback != NULL) {
1976           (*callback)(env->jvmti_external(), jni_env, jem.jni_thread(),
1977                       jem.jni_methodID(), (void*)(*function_ptr), (void**)function_ptr);
1978         }
1979       }
1980     }
1981   }
1982 }
1983 
1984 // Returns a record containing inlining information for the given nmethod
1985 jvmtiCompiledMethodLoadInlineRecord* create_inline_record(nmethod* nm) {
1986   jint numstackframes = 0;
1987   jvmtiCompiledMethodLoadInlineRecord* record = (jvmtiCompiledMethodLoadInlineRecord*)NEW_RESOURCE_OBJ(jvmtiCompiledMethodLoadInlineRecord);
1988   record->header.kind = JVMTI_CMLR_INLINE_INFO;
1989   record->header.next = NULL;
1990   record->header.majorinfoversion = JVMTI_CMLR_MAJOR_VERSION_1;
1991   record->header.minorinfoversion = JVMTI_CMLR_MINOR_VERSION_0;
1992   record->numpcs = 0;
1993   for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
1994    if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
1995    record->numpcs++;
1996   }
1997   record->pcinfo = (PCStackInfo*)(NEW_RESOURCE_ARRAY(PCStackInfo, record->numpcs));
1998   int scope = 0;
1999   for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
2000     if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
2001     void* pc_address = (void*)p->real_pc(nm);
2002     assert(pc_address != NULL, "pc_address must be non-null");
2003     record->pcinfo[scope].pc = pc_address;
2004     numstackframes=0;
2005     for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2006       numstackframes++;
2007     }
2008     assert(numstackframes != 0, "numstackframes must be nonzero.");
2009     record->pcinfo[scope].methods = (jmethodID *)NEW_RESOURCE_ARRAY(jmethodID, numstackframes);
2010     record->pcinfo[scope].bcis = (jint *)NEW_RESOURCE_ARRAY(jint, numstackframes);
2011     record->pcinfo[scope].numstackframes = numstackframes;
2012     int stackframe = 0;
2013     for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2014       // 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()
2015       assert(sd->method() != NULL, "sd->method() cannot be null.");
2016       record->pcinfo[scope].methods[stackframe] = sd->method()->jmethod_id();
2017       record->pcinfo[scope].bcis[stackframe] = sd->bci();
2018       stackframe++;
2019     }
2020     scope++;
2021   }
2022   return record;
2023 }
2024 
2025 void JvmtiExport::post_compiled_method_load(nmethod *nm) {
2026   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
2027     return;
2028   }
2029   JavaThread* thread = JavaThread::current();
2030 
2031   EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2032                  ("[%s] method compile load event triggered",
2033                  JvmtiTrace::safe_get_thread_name(thread)));
2034 
2035   JvmtiEnvIterator it;
2036   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2037     if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
2038       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
2039         continue;
2040       }
2041       EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2042                 ("[%s] class compile method load event sent %s.%s  ",
2043                 JvmtiTrace::safe_get_thread_name(thread),
2044                 (nm->method() == NULL) ? "NULL" : nm->method()->klass_name()->as_C_string(),
2045                 (nm->method() == NULL) ? "NULL" : nm->method()->name()->as_C_string()));
2046       ResourceMark rm(thread);
2047       HandleMark hm(thread);
2048 
2049       // Add inlining information
2050       jvmtiCompiledMethodLoadInlineRecord* inlinerecord = create_inline_record(nm);
2051       // Pass inlining information through the void pointer
2052       JvmtiCompiledMethodLoadEventMark jem(thread, nm, inlinerecord);
2053       JvmtiJavaThreadEventTransition jet(thread);
2054       jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
2055       if (callback != NULL) {
2056         (*callback)(env->jvmti_external(), jem.jni_methodID(),
2057                     jem.code_size(), jem.code_data(), jem.map_length(),
2058                     jem.map(), jem.compile_info());
2059       }
2060     }
2061   }
2062 }
2063 
2064 
2065 // post a COMPILED_METHOD_LOAD event for a given environment
2066 void JvmtiExport::post_compiled_method_load(JvmtiEnv* env, const jmethodID method, const jint length,
2067                                             const void *code_begin, const jint map_length,
2068                                             const jvmtiAddrLocationMap* map)
2069 {
2070   if (env->phase() <= JVMTI_PHASE_PRIMORDIAL) {
2071     return;
2072   }
2073   JavaThread* thread = JavaThread::current();
2074   EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2075                  ("[%s] method compile load event triggered (by GenerateEvents)",
2076                  JvmtiTrace::safe_get_thread_name(thread)));
2077   if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
2078 
2079     EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2080               ("[%s] class compile method load event sent (by GenerateEvents), jmethodID=" PTR_FORMAT,
2081                JvmtiTrace::safe_get_thread_name(thread), p2i(method)));
2082 
2083     JvmtiEventMark jem(thread);
2084     JvmtiJavaThreadEventTransition jet(thread);
2085     jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
2086     if (callback != NULL) {
2087       (*callback)(env->jvmti_external(), method,
2088                   length, code_begin, map_length,
2089                   map, NULL);
2090     }
2091   }
2092 }
2093 
2094 void JvmtiExport::post_dynamic_code_generated_internal(const char *name, const void *code_begin, const void *code_end) {
2095   assert(name != NULL && name[0] != '\0', "sanity check");
2096 
2097   JavaThread* thread = JavaThread::current();
2098   // In theory everyone coming thru here is in_vm but we need to be certain
2099   // because a callee will do a vm->native transition
2100   ThreadInVMfromUnknown __tiv;
2101 
2102   EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2103                  ("[%s] method dynamic code generated event triggered",
2104                  JvmtiTrace::safe_get_thread_name(thread)));
2105   JvmtiEnvIterator it;
2106   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2107     if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2108       EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2109                 ("[%s] dynamic code generated event sent for %s",
2110                 JvmtiTrace::safe_get_thread_name(thread), name));
2111       JvmtiEventMark jem(thread);
2112       JvmtiJavaThreadEventTransition jet(thread);
2113       jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2114       jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2115       if (callback != NULL) {
2116         (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2117       }
2118     }
2119   }
2120 }
2121 
2122 void JvmtiExport::post_dynamic_code_generated(const char *name, const void *code_begin, const void *code_end) {
2123   jvmtiPhase phase = JvmtiEnv::get_phase();
2124   if (phase == JVMTI_PHASE_PRIMORDIAL || phase == JVMTI_PHASE_START) {
2125     post_dynamic_code_generated_internal(name, code_begin, code_end);
2126   } else {
2127     // It may not be safe to post the event from this thread.  Defer all
2128     // postings to the service thread so that it can perform them in a safe
2129     // context and in-order.
2130     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
2131     JvmtiDeferredEvent event = JvmtiDeferredEvent::dynamic_code_generated_event(
2132         name, code_begin, code_end);
2133     JvmtiDeferredEventQueue::enqueue(event);
2134   }
2135 }
2136 
2137 
2138 // post a DYNAMIC_CODE_GENERATED event for a given environment
2139 // used by GenerateEvents
2140 void JvmtiExport::post_dynamic_code_generated(JvmtiEnv* env, const char *name,
2141                                               const void *code_begin, const void *code_end)
2142 {
2143   JavaThread* thread = JavaThread::current();
2144   EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2145                  ("[%s] dynamic code generated event triggered (by GenerateEvents)",
2146                   JvmtiTrace::safe_get_thread_name(thread)));
2147   if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2148     EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2149               ("[%s] dynamic code generated event sent for %s",
2150                JvmtiTrace::safe_get_thread_name(thread), name));
2151     JvmtiEventMark jem(thread);
2152     JvmtiJavaThreadEventTransition jet(thread);
2153     jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2154     jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2155     if (callback != NULL) {
2156       (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2157     }
2158   }
2159 }
2160 
2161 // post a DynamicCodeGenerated event while holding locks in the VM.
2162 void JvmtiExport::post_dynamic_code_generated_while_holding_locks(const char* name,
2163                                                                   address code_begin, address code_end)
2164 {
2165   // register the stub with the current dynamic code event collector
2166   JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
2167   // state can only be NULL if the current thread is exiting which
2168   // should not happen since we're trying to post an event
2169   guarantee(state != NULL, "attempt to register stub via an exiting thread");
2170   JvmtiDynamicCodeEventCollector* collector = state->get_dynamic_code_event_collector();
2171   guarantee(collector != NULL, "attempt to register stub without event collector");
2172   collector->register_stub(name, code_begin, code_end);
2173 }
2174 
2175 // Collect all the vm internally allocated objects which are visible to java world
2176 void JvmtiExport::record_vm_internal_object_allocation(oop obj) {
2177   Thread* thread = Thread::current_or_null();
2178   if (thread != NULL && thread->is_Java_thread())  {
2179     // Can not take safepoint here.
2180     NoSafepointVerifier no_sfpt;
2181     // Can not take safepoint here so can not use state_for to get
2182     // jvmti thread state.
2183     JvmtiThreadState *state = ((JavaThread*)thread)->jvmti_thread_state();
2184     if (state != NULL ) {
2185       // state is non NULL when VMObjectAllocEventCollector is enabled.
2186       JvmtiVMObjectAllocEventCollector *collector;
2187       collector = state->get_vm_object_alloc_event_collector();
2188       if (collector != NULL && collector->is_enabled()) {
2189         // Don't record classes as these will be notified via the ClassLoad
2190         // event.
2191         if (obj->klass() != SystemDictionary::Class_klass()) {
2192           collector->record_allocation(obj);
2193         }
2194       }
2195     }
2196   }
2197 }
2198 
2199 void JvmtiExport::post_garbage_collection_finish() {
2200   Thread *thread = Thread::current(); // this event is posted from VM-Thread.
2201   EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2202                  ("[%s] garbage collection finish event triggered",
2203                   JvmtiTrace::safe_get_thread_name(thread)));
2204   JvmtiEnvIterator it;
2205   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2206     if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH)) {
2207       EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2208                 ("[%s] garbage collection finish event sent",
2209                  JvmtiTrace::safe_get_thread_name(thread)));
2210       JvmtiThreadEventTransition jet(thread);
2211       // JNIEnv is NULL here because this event is posted from VM Thread
2212       jvmtiEventGarbageCollectionFinish callback = env->callbacks()->GarbageCollectionFinish;
2213       if (callback != NULL) {
2214         (*callback)(env->jvmti_external());
2215       }
2216     }
2217   }
2218 }
2219 
2220 void JvmtiExport::post_garbage_collection_start() {
2221   Thread* thread = Thread::current(); // this event is posted from vm-thread.
2222   EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2223                  ("[%s] garbage collection start event triggered",
2224                   JvmtiTrace::safe_get_thread_name(thread)));
2225   JvmtiEnvIterator it;
2226   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2227     if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_START)) {
2228       EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2229                 ("[%s] garbage collection start event sent",
2230                  JvmtiTrace::safe_get_thread_name(thread)));
2231       JvmtiThreadEventTransition jet(thread);
2232       // JNIEnv is NULL here because this event is posted from VM Thread
2233       jvmtiEventGarbageCollectionStart callback = env->callbacks()->GarbageCollectionStart;
2234       if (callback != NULL) {
2235         (*callback)(env->jvmti_external());
2236       }
2237     }
2238   }
2239 }
2240 
2241 void JvmtiExport::post_data_dump() {
2242   Thread *thread = Thread::current();
2243   EVT_TRIG_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2244                  ("[%s] data dump request event triggered",
2245                   JvmtiTrace::safe_get_thread_name(thread)));
2246   JvmtiEnvIterator it;
2247   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2248     if (env->is_enabled(JVMTI_EVENT_DATA_DUMP_REQUEST)) {
2249       EVT_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2250                 ("[%s] data dump request event sent",
2251                  JvmtiTrace::safe_get_thread_name(thread)));
2252      JvmtiThreadEventTransition jet(thread);
2253      // JNIEnv is NULL here because this event is posted from VM Thread
2254      jvmtiEventDataDumpRequest callback = env->callbacks()->DataDumpRequest;
2255      if (callback != NULL) {
2256        (*callback)(env->jvmti_external());
2257      }
2258     }
2259   }
2260 }
2261 
2262 void JvmtiExport::post_monitor_contended_enter(JavaThread *thread, ObjectMonitor *obj_mntr) {
2263   oop object = (oop)obj_mntr->object();
2264   if (!ServiceUtil::visible_oop(object)) {
2265     // Ignore monitor contended enter for vm internal object.
2266     return;
2267   }
2268   JvmtiThreadState *state = thread->jvmti_thread_state();
2269   if (state == NULL) {
2270     return;
2271   }
2272 
2273   HandleMark hm(thread);
2274   Handle h(thread, object);
2275 
2276   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2277                      ("[%s] montior contended enter event triggered",
2278                       JvmtiTrace::safe_get_thread_name(thread)));
2279 
2280   JvmtiEnvThreadStateIterator it(state);
2281   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2282     if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTER)) {
2283       EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2284                    ("[%s] monitor contended enter event sent",
2285                     JvmtiTrace::safe_get_thread_name(thread)));
2286       JvmtiMonitorEventMark  jem(thread, h());
2287       JvmtiEnv *env = ets->get_env();
2288       JvmtiThreadEventTransition jet(thread);
2289       jvmtiEventMonitorContendedEnter callback = env->callbacks()->MonitorContendedEnter;
2290       if (callback != NULL) {
2291         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2292       }
2293     }
2294   }
2295 }
2296 
2297 void JvmtiExport::post_monitor_contended_entered(JavaThread *thread, ObjectMonitor *obj_mntr) {
2298   oop object = (oop)obj_mntr->object();
2299   if (!ServiceUtil::visible_oop(object)) {
2300     // Ignore monitor contended entered for vm internal object.
2301     return;
2302   }
2303   JvmtiThreadState *state = thread->jvmti_thread_state();
2304   if (state == NULL) {
2305     return;
2306   }
2307 
2308   HandleMark hm(thread);
2309   Handle h(thread, object);
2310 
2311   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2312                      ("[%s] montior contended entered event triggered",
2313                       JvmtiTrace::safe_get_thread_name(thread)));
2314 
2315   JvmtiEnvThreadStateIterator it(state);
2316   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2317     if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED)) {
2318       EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2319                    ("[%s] monitor contended enter event sent",
2320                     JvmtiTrace::safe_get_thread_name(thread)));
2321       JvmtiMonitorEventMark  jem(thread, h());
2322       JvmtiEnv *env = ets->get_env();
2323       JvmtiThreadEventTransition jet(thread);
2324       jvmtiEventMonitorContendedEntered callback = env->callbacks()->MonitorContendedEntered;
2325       if (callback != NULL) {
2326         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2327       }
2328     }
2329   }
2330 }
2331 
2332 void JvmtiExport::post_monitor_wait(JavaThread *thread, oop object,
2333                                           jlong timeout) {
2334   JvmtiThreadState *state = thread->jvmti_thread_state();
2335   if (state == NULL) {
2336     return;
2337   }
2338 
2339   HandleMark hm(thread);
2340   Handle h(thread, object);
2341 
2342   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2343                      ("[%s] montior wait event triggered",
2344                       JvmtiTrace::safe_get_thread_name(thread)));
2345 
2346   JvmtiEnvThreadStateIterator it(state);
2347   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2348     if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAIT)) {
2349       EVT_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2350                    ("[%s] monitor wait event sent",
2351                     JvmtiTrace::safe_get_thread_name(thread)));
2352       JvmtiMonitorEventMark  jem(thread, h());
2353       JvmtiEnv *env = ets->get_env();
2354       JvmtiThreadEventTransition jet(thread);
2355       jvmtiEventMonitorWait callback = env->callbacks()->MonitorWait;
2356       if (callback != NULL) {
2357         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2358                     jem.jni_object(), timeout);
2359       }
2360     }
2361   }
2362 }
2363 
2364 void JvmtiExport::post_monitor_waited(JavaThread *thread, ObjectMonitor *obj_mntr, jboolean timed_out) {
2365   oop object = (oop)obj_mntr->object();
2366   if (!ServiceUtil::visible_oop(object)) {
2367     // Ignore monitor waited for vm internal object.
2368     return;
2369   }
2370   JvmtiThreadState *state = thread->jvmti_thread_state();
2371   if (state == NULL) {
2372     return;
2373   }
2374 
2375   HandleMark hm(thread);
2376   Handle h(thread, object);
2377 
2378   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2379                      ("[%s] montior waited event triggered",
2380                       JvmtiTrace::safe_get_thread_name(thread)));
2381 
2382   JvmtiEnvThreadStateIterator it(state);
2383   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2384     if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAITED)) {
2385       EVT_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2386                    ("[%s] monitor waited event sent",
2387                     JvmtiTrace::safe_get_thread_name(thread)));
2388       JvmtiMonitorEventMark  jem(thread, h());
2389       JvmtiEnv *env = ets->get_env();
2390       JvmtiThreadEventTransition jet(thread);
2391       jvmtiEventMonitorWaited callback = env->callbacks()->MonitorWaited;
2392       if (callback != NULL) {
2393         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2394                     jem.jni_object(), timed_out);
2395       }
2396     }
2397   }
2398 }
2399 
2400 
2401 void JvmtiExport::post_vm_object_alloc(JavaThread *thread,  oop object) {
2402   EVT_TRIG_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Trg vm object alloc triggered",
2403                       JvmtiTrace::safe_get_thread_name(thread)));
2404   if (object == NULL) {
2405     return;
2406   }
2407   HandleMark hm(thread);
2408   Handle h(thread, object);
2409   JvmtiEnvIterator it;
2410   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2411     if (env->is_enabled(JVMTI_EVENT_VM_OBJECT_ALLOC)) {
2412       EVT_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Evt vmobject alloc sent %s",
2413                                          JvmtiTrace::safe_get_thread_name(thread),
2414                                          object==NULL? "NULL" : object->klass()->external_name()));
2415 
2416       JvmtiVMObjectAllocEventMark jem(thread, h());
2417       JvmtiJavaThreadEventTransition jet(thread);
2418       jvmtiEventVMObjectAlloc callback = env->callbacks()->VMObjectAlloc;
2419       if (callback != NULL) {
2420         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2421                     jem.jni_jobject(), jem.jni_class(), jem.size());
2422       }
2423     }
2424   }
2425 }
2426 
2427 ////////////////////////////////////////////////////////////////////////////////////////////////
2428 
2429 void JvmtiExport::cleanup_thread(JavaThread* thread) {
2430   assert(JavaThread::current() == thread, "thread is not current");
2431   MutexLocker mu(JvmtiThreadState_lock);
2432 
2433   if (thread->jvmti_thread_state() != NULL) {
2434     // This has to happen after the thread state is removed, which is
2435     // why it is not in post_thread_end_event like its complement
2436     // Maybe both these functions should be rolled into the posts?
2437     JvmtiEventController::thread_ended(thread);
2438   }
2439 }
2440 
2441 void JvmtiExport::clear_detected_exception(JavaThread* thread) {
2442   assert(JavaThread::current() == thread, "thread is not current");
2443 
2444   JvmtiThreadState* state = thread->jvmti_thread_state();
2445   if (state != NULL) {
2446     state->clear_exception_state();
2447   }
2448 }
2449 
2450 void JvmtiExport::oops_do(OopClosure* f) {
2451   JvmtiCurrentBreakpoints::oops_do(f);
2452   JvmtiVMObjectAllocEventCollector::oops_do_for_all_threads(f);
2453 }
2454 
2455 void JvmtiExport::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f) {
2456   JvmtiTagMap::weak_oops_do(is_alive, f);
2457 }
2458 
2459 void JvmtiExport::gc_epilogue() {
2460   JvmtiCurrentBreakpoints::gc_epilogue();
2461 }
2462 
2463 // Onload raw monitor transition.
2464 void JvmtiExport::transition_pending_onload_raw_monitors() {
2465   JvmtiPendingMonitors::transition_raw_monitors();
2466 }
2467 
2468 ////////////////////////////////////////////////////////////////////////////////////////////////
2469 #if INCLUDE_SERVICES
2470 // Attach is disabled if SERVICES is not included
2471 
2472 // type for the Agent_OnAttach entry point
2473 extern "C" {
2474   typedef jint (JNICALL *OnAttachEntry_t)(JavaVM*, char *, void *);
2475 }
2476 
2477 jint JvmtiExport::load_agent_library(AttachOperation* op, outputStream* st) {
2478   // get agent name and options
2479   const char* agent = op->arg(0);
2480   const char* absParam = op->arg(1);
2481   const char* options = op->arg(2);
2482 
2483   return load_agent_library(agent, absParam, options, st);
2484 }
2485 
2486 jint JvmtiExport::load_agent_library(const char *agent, const char *absParam,
2487                                      const char *options, outputStream* st) {
2488   char ebuf[1024];
2489   char buffer[JVM_MAXPATHLEN];
2490   void* library = NULL;
2491   jint result = JNI_ERR;
2492   const char *on_attach_symbols[] = AGENT_ONATTACH_SYMBOLS;
2493   size_t num_symbol_entries = ARRAY_SIZE(on_attach_symbols);
2494 
2495   // The abs paramter should be "true" or "false"
2496   bool is_absolute_path = (absParam != NULL) && (strcmp(absParam,"true")==0);
2497 
2498   // Initially marked as invalid. It will be set to valid if we can find the agent
2499   AgentLibrary *agent_lib = new AgentLibrary(agent, options, is_absolute_path, NULL);
2500 
2501   // Check for statically linked in agent. If not found then if the path is
2502   // absolute we attempt to load the library. Otherwise we try to load it
2503   // from the standard dll directory.
2504 
2505   if (!os::find_builtin_agent(agent_lib, on_attach_symbols, num_symbol_entries)) {
2506     if (is_absolute_path) {
2507       library = os::dll_load(agent, ebuf, sizeof ebuf);
2508     } else {
2509       // Try to load the agent from the standard dll directory
2510       if (os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
2511                              agent)) {
2512         library = os::dll_load(buffer, ebuf, sizeof ebuf);
2513       }
2514       if (library == NULL) {
2515         // not found - try local path
2516         char ns[1] = {0};
2517         if (os::dll_build_name(buffer, sizeof(buffer), ns, agent)) {
2518           library = os::dll_load(buffer, ebuf, sizeof ebuf);
2519         }
2520       }
2521     }
2522     if (library != NULL) {
2523       agent_lib->set_os_lib(library);
2524       agent_lib->set_valid();
2525     }
2526   }
2527   // If the library was loaded then we attempt to invoke the Agent_OnAttach
2528   // function
2529   if (agent_lib->valid()) {
2530     // Lookup the Agent_OnAttach function
2531     OnAttachEntry_t on_attach_entry = NULL;
2532     on_attach_entry = CAST_TO_FN_PTR(OnAttachEntry_t,
2533        os::find_agent_function(agent_lib, false, on_attach_symbols, num_symbol_entries));
2534     if (on_attach_entry == NULL) {
2535       // Agent_OnAttach missing - unload library
2536       if (!agent_lib->is_static_lib()) {
2537         os::dll_unload(library);
2538       }
2539       delete agent_lib;
2540     } else {
2541       // Invoke the Agent_OnAttach function
2542       JavaThread* THREAD = JavaThread::current();
2543       {
2544         extern struct JavaVM_ main_vm;
2545         JvmtiThreadEventMark jem(THREAD);
2546         JvmtiJavaThreadEventTransition jet(THREAD);
2547 
2548         result = (*on_attach_entry)(&main_vm, (char*)options, NULL);
2549       }
2550 
2551       // Agent_OnAttach may have used JNI
2552       if (HAS_PENDING_EXCEPTION) {
2553         CLEAR_PENDING_EXCEPTION;
2554       }
2555 
2556       // If OnAttach returns JNI_OK then we add it to the list of
2557       // agent libraries so that we can call Agent_OnUnload later.
2558       if (result == JNI_OK) {
2559         Arguments::add_loaded_agent(agent_lib);
2560       } else {
2561         delete agent_lib;
2562       }
2563 
2564       // Agent_OnAttach executed so completion status is JNI_OK
2565       st->print_cr("%d", result);
2566       result = JNI_OK;
2567     }
2568   }
2569   return result;
2570 }
2571 
2572 #endif // INCLUDE_SERVICES
2573 ////////////////////////////////////////////////////////////////////////////////////////////////
2574 
2575 // Setup current current thread for event collection.
2576 void JvmtiEventCollector::setup_jvmti_thread_state() {
2577   // set this event collector to be the current one.
2578   JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
2579   // state can only be NULL if the current thread is exiting which
2580   // should not happen since we're trying to configure for event collection
2581   guarantee(state != NULL, "exiting thread called setup_jvmti_thread_state");
2582   if (is_vm_object_alloc_event()) {
2583     _prev = state->get_vm_object_alloc_event_collector();
2584     state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)this);
2585   } else if (is_dynamic_code_event()) {
2586     _prev = state->get_dynamic_code_event_collector();
2587     state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)this);
2588   }
2589 }
2590 
2591 // Unset current event collection in this thread and reset it with previous
2592 // collector.
2593 void JvmtiEventCollector::unset_jvmti_thread_state() {
2594   JvmtiThreadState* state = JavaThread::current()->jvmti_thread_state();
2595   if (state != NULL) {
2596     // restore the previous event collector (if any)
2597     if (is_vm_object_alloc_event()) {
2598       if (state->get_vm_object_alloc_event_collector() == this) {
2599         state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)_prev);
2600       } else {
2601         // this thread's jvmti state was created during the scope of
2602         // the event collector.
2603       }
2604     } else {
2605       if (is_dynamic_code_event()) {
2606         if (state->get_dynamic_code_event_collector() == this) {
2607           state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)_prev);
2608         } else {
2609           // this thread's jvmti state was created during the scope of
2610           // the event collector.
2611         }
2612       }
2613     }
2614   }
2615 }
2616 
2617 // create the dynamic code event collector
2618 JvmtiDynamicCodeEventCollector::JvmtiDynamicCodeEventCollector() : _code_blobs(NULL) {
2619   if (JvmtiExport::should_post_dynamic_code_generated()) {
2620     setup_jvmti_thread_state();
2621   }
2622 }
2623 
2624 // iterate over any code blob descriptors collected and post a
2625 // DYNAMIC_CODE_GENERATED event to the profiler.
2626 JvmtiDynamicCodeEventCollector::~JvmtiDynamicCodeEventCollector() {
2627   assert(!JavaThread::current()->owns_locks(), "all locks must be released to post deferred events");
2628  // iterate over any code blob descriptors that we collected
2629  if (_code_blobs != NULL) {
2630    for (int i=0; i<_code_blobs->length(); i++) {
2631      JvmtiCodeBlobDesc* blob = _code_blobs->at(i);
2632      JvmtiExport::post_dynamic_code_generated(blob->name(), blob->code_begin(), blob->code_end());
2633      FreeHeap(blob);
2634    }
2635    delete _code_blobs;
2636  }
2637  unset_jvmti_thread_state();
2638 }
2639 
2640 // register a stub
2641 void JvmtiDynamicCodeEventCollector::register_stub(const char* name, address start, address end) {
2642  if (_code_blobs == NULL) {
2643    _code_blobs = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JvmtiCodeBlobDesc*>(1,true);
2644  }
2645  _code_blobs->append(new JvmtiCodeBlobDesc(name, start, end));
2646 }
2647 
2648 // Setup current thread to record vm allocated objects.
2649 JvmtiVMObjectAllocEventCollector::JvmtiVMObjectAllocEventCollector() : _allocated(NULL) {
2650   if (JvmtiExport::should_post_vm_object_alloc()) {
2651     _enable = true;
2652     setup_jvmti_thread_state();
2653   } else {
2654     _enable = false;
2655   }
2656 }
2657 
2658 // Post vm_object_alloc event for vm allocated objects visible to java
2659 // world.
2660 JvmtiVMObjectAllocEventCollector::~JvmtiVMObjectAllocEventCollector() {
2661   if (_allocated != NULL) {
2662     set_enabled(false);
2663     for (int i = 0; i < _allocated->length(); i++) {
2664       oop obj = _allocated->at(i);
2665       if (ServiceUtil::visible_oop(obj)) {
2666         JvmtiExport::post_vm_object_alloc(JavaThread::current(), obj);
2667       }
2668     }
2669     delete _allocated;
2670   }
2671   unset_jvmti_thread_state();
2672 }
2673 
2674 void JvmtiVMObjectAllocEventCollector::record_allocation(oop obj) {
2675   assert(is_enabled(), "VM object alloc event collector is not enabled");
2676   if (_allocated == NULL) {
2677     _allocated = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(1, true);
2678   }
2679   _allocated->push(obj);
2680 }
2681 
2682 // GC support.
2683 void JvmtiVMObjectAllocEventCollector::oops_do(OopClosure* f) {
2684   if (_allocated != NULL) {
2685     for(int i=_allocated->length() - 1; i >= 0; i--) {
2686       if (_allocated->at(i) != NULL) {
2687         f->do_oop(_allocated->adr_at(i));
2688       }
2689     }
2690   }
2691 }
2692 
2693 void JvmtiVMObjectAllocEventCollector::oops_do_for_all_threads(OopClosure* f) {
2694   // no-op if jvmti not enabled
2695   if (!JvmtiEnv::environments_might_exist()) {
2696     return;
2697   }
2698 
2699   // Runs at safepoint. So no need to acquire Threads_lock.
2700   for (JavaThread *jthr = Threads::first(); jthr != NULL; jthr = jthr->next()) {
2701     JvmtiThreadState *state = jthr->jvmti_thread_state();
2702     if (state != NULL) {
2703       JvmtiVMObjectAllocEventCollector *collector;
2704       collector = state->get_vm_object_alloc_event_collector();
2705       while (collector != NULL) {
2706         collector->oops_do(f);
2707         collector = (JvmtiVMObjectAllocEventCollector *)collector->get_prev();
2708       }
2709     }
2710   }
2711 }
2712 
2713 
2714 // Disable collection of VMObjectAlloc events
2715 NoJvmtiVMObjectAllocMark::NoJvmtiVMObjectAllocMark() : _collector(NULL) {
2716   // a no-op if VMObjectAlloc event is not enabled
2717   if (!JvmtiExport::should_post_vm_object_alloc()) {
2718     return;
2719   }
2720   Thread* thread = Thread::current_or_null();
2721   if (thread != NULL && thread->is_Java_thread())  {
2722     JavaThread* current_thread = (JavaThread*)thread;
2723     JvmtiThreadState *state = current_thread->jvmti_thread_state();
2724     if (state != NULL) {
2725       JvmtiVMObjectAllocEventCollector *collector;
2726       collector = state->get_vm_object_alloc_event_collector();
2727       if (collector != NULL && collector->is_enabled()) {
2728         _collector = collector;
2729         _collector->set_enabled(false);
2730       }
2731     }
2732   }
2733 }
2734 
2735 // Re-Enable collection of VMObjectAlloc events (if previously enabled)
2736 NoJvmtiVMObjectAllocMark::~NoJvmtiVMObjectAllocMark() {
2737   if (was_enabled()) {
2738     _collector->set_enabled(true);
2739   }
2740 };
2741 
2742 JvmtiGCMarker::JvmtiGCMarker() {
2743   // if there aren't any JVMTI environments then nothing to do
2744   if (!JvmtiEnv::environments_might_exist()) {
2745     return;
2746   }
2747 
2748   if (JvmtiExport::should_post_garbage_collection_start()) {
2749     JvmtiExport::post_garbage_collection_start();
2750   }
2751 
2752   if (SafepointSynchronize::is_at_safepoint()) {
2753     // Do clean up tasks that need to be done at a safepoint
2754     JvmtiEnvBase::check_for_periodic_clean_up();
2755   }
2756 }
2757 
2758 JvmtiGCMarker::~JvmtiGCMarker() {
2759   // if there aren't any JVMTI environments then nothing to do
2760   if (!JvmtiEnv::environments_might_exist()) {
2761     return;
2762   }
2763 
2764   // JVMTI notify gc finish
2765   if (JvmtiExport::should_post_garbage_collection_finish()) {
2766     JvmtiExport::post_garbage_collection_finish();
2767   }
2768 }
--- EOF ---