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