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