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