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