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