1 /*
   2  * Copyright (c) 2003, 2021, 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/vmClasses.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/nmethod.hpp"
  31 #include "code/pcDesc.hpp"
  32 #include "code/scopeDesc.hpp"
  33 #include "gc/shared/oopStorageSet.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "jvmtifiles/jvmtiEnv.hpp"
  36 #include "logging/log.hpp"
  37 #include "logging/logStream.hpp"
  38 #include "memory/allocation.inline.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "memory/universe.hpp"
  41 #include "oops/klass.inline.hpp"
  42 #include "oops/objArrayKlass.hpp"
  43 #include "oops/objArrayOop.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "oops/oopHandle.inline.hpp"
  46 #include "prims/jvmtiCodeBlobEvents.hpp"
  47 #include "prims/jvmtiEventController.hpp"
  48 #include "prims/jvmtiEventController.inline.hpp"
  49 #include "prims/jvmtiExport.hpp"
  50 #include "prims/jvmtiImpl.hpp"
  51 #include "prims/jvmtiManageCapabilities.hpp"
  52 #include "prims/jvmtiRawMonitor.hpp"
  53 #include "prims/jvmtiRedefineClasses.hpp"
  54 #include "prims/jvmtiTagMap.hpp"
  55 #include "prims/jvmtiThreadState.inline.hpp"
  56 #include "runtime/arguments.hpp"
  57 #include "runtime/fieldDescriptor.inline.hpp"
  58 #include "runtime/handles.inline.hpp"
  59 #include "runtime/interfaceSupport.inline.hpp"
  60 #include "runtime/javaCalls.hpp"
  61 #include "runtime/jniHandles.inline.hpp"
  62 #include "runtime/objectMonitor.hpp"
  63 #include "runtime/objectMonitor.inline.hpp"
  64 #include "runtime/os.hpp"
  65 #include "runtime/osThread.hpp"
  66 #include "runtime/safepointVerifiers.hpp"
  67 #include "runtime/serviceThread.hpp"
  68 #include "runtime/thread.inline.hpp"
  69 #include "runtime/threadSMR.hpp"
  70 #include "runtime/vframe.inline.hpp"
  71 #include "runtime/vm_version.hpp"
  72 #include "utilities/macros.hpp"
  73 
  74 #ifdef JVMTI_TRACE
  75 #define EVT_TRACE(evt,out) if ((JvmtiTrace::event_trace_flags(evt) & JvmtiTrace::SHOW_EVENT_SENT) != 0) { SafeResourceMark rm; log_trace(jvmti) out; }
  76 #define EVT_TRIG_TRACE(evt,out) if ((JvmtiTrace::event_trace_flags(evt) & JvmtiTrace::SHOW_EVENT_TRIGGER) != 0) { SafeResourceMark rm; log_trace(jvmti) out; }
  77 #else
  78 #define EVT_TRIG_TRACE(evt,out)
  79 #define EVT_TRACE(evt,out)
  80 #endif
  81 
  82 ///////////////////////////////////////////////////////////////
  83 //
  84 // JvmtiEventTransition
  85 //
  86 // TO DO --
  87 //  more handle purging
  88 
  89 // Use this for JavaThreads and state is  _thread_in_vm.
  90 class JvmtiJavaThreadEventTransition : StackObj {
  91 private:
  92   ResourceMark _rm;
  93   ThreadToNativeFromVM _transition;
  94   HandleMark _hm;
  95 
  96 public:
  97   JvmtiJavaThreadEventTransition(JavaThread *thread) :
  98     _rm(),
  99     _transition(thread),
 100     _hm(thread)  {};
 101 };
 102 
 103 // For JavaThreads which are not in _thread_in_vm state
 104 // and other system threads use this.
 105 class JvmtiThreadEventTransition : StackObj {
 106 private:
 107   ResourceMark _rm;
 108   HandleMark _hm;
 109   JavaThreadState _saved_state;
 110   JavaThread *_jthread;
 111 
 112 public:
 113   JvmtiThreadEventTransition(Thread *thread) : _rm(), _hm(thread) {
 114     if (thread->is_Java_thread()) {
 115        _jthread = JavaThread::cast(thread);
 116        _saved_state = _jthread->thread_state();
 117        if (_saved_state == _thread_in_Java) {
 118          ThreadStateTransition::transition_from_java(_jthread, _thread_in_native);
 119        } else {
 120          ThreadStateTransition::transition_from_vm(_jthread, _thread_in_native);
 121        }
 122     } else {
 123       _jthread = NULL;
 124     }
 125   }
 126 
 127   ~JvmtiThreadEventTransition() {
 128     if (_jthread != NULL)
 129       ThreadStateTransition::transition_from_native(_jthread, _saved_state);
 130   }
 131 };
 132 
 133 
 134 ///////////////////////////////////////////////////////////////
 135 //
 136 // JvmtiEventMark
 137 //
 138 
 139 class JvmtiEventMark : public StackObj {
 140 private:
 141   JavaThread *_thread;
 142   JNIEnv* _jni_env;
 143   JvmtiThreadState::ExceptionState _saved_exception_state;
 144 
 145 public:
 146   JvmtiEventMark(JavaThread *thread) :  _thread(thread),
 147                                         _jni_env(thread->jni_environment()),
 148                                         _saved_exception_state(JvmtiThreadState::ES_CLEARED) {
 149     JvmtiThreadState *state = thread->jvmti_thread_state();
 150     // we are before an event.
 151     // Save current jvmti thread exception state.
 152     if (state != NULL) {
 153       _saved_exception_state = state->get_exception_state();
 154     }
 155 
 156     thread->push_jni_handle_block();
 157     assert(thread == JavaThread::current(), "thread must be current!");
 158     thread->frame_anchor()->make_walkable(thread);
 159   };
 160 
 161   ~JvmtiEventMark() {
 162     _thread->pop_jni_handle_block();
 163 
 164     JvmtiThreadState* state = _thread->jvmti_thread_state();
 165     // we are continuing after an event.
 166     if (state != NULL) {
 167       // Restore the jvmti thread exception state.
 168       state->restore_exception_state(_saved_exception_state);
 169     }
 170   }
 171 
 172   jobject to_jobject(oop obj) { return JNIHandles::make_local(_thread,obj); }
 173 
 174   jclass to_jclass(Klass* klass) { return (klass == NULL ? NULL : (jclass)to_jobject(klass->java_mirror())); }
 175 
 176   jmethodID to_jmethodID(const methodHandle& method) { return method->jmethod_id(); }
 177 
 178   JNIEnv* jni_env() { return _jni_env; }
 179 };
 180 
 181 class JvmtiThreadEventMark : public JvmtiEventMark {
 182 private:
 183   jthread _jt;
 184 
 185 public:
 186   JvmtiThreadEventMark(JavaThread *thread) :
 187     JvmtiEventMark(thread) {
 188     _jt = (jthread)(to_jobject(thread->threadObj()));
 189   };
 190  jthread jni_thread() { return _jt; }
 191 };
 192 
 193 class JvmtiClassEventMark : public JvmtiThreadEventMark {

















 194 private:
 195   jclass _jc;
 196 
 197 public:
 198   JvmtiClassEventMark(JavaThread *thread, Klass* klass) :
 199     JvmtiThreadEventMark(thread) {
 200     _jc = to_jclass(klass);
 201   };
 202   jclass jni_class() { return _jc; }
 203 };
 204 
 205 class JvmtiMethodEventMark : public JvmtiThreadEventMark {
 206 private:
 207   jmethodID _mid;
 208 
 209 public:
 210   JvmtiMethodEventMark(JavaThread *thread, const methodHandle& method) :
 211     JvmtiThreadEventMark(thread),
 212     _mid(to_jmethodID(method)) {};
 213   jmethodID jni_methodID() { return _mid; }
 214 };
 215 
 216 class JvmtiLocationEventMark : public JvmtiMethodEventMark {
 217 private:
 218   jlocation _loc;
 219 
 220 public:
 221   JvmtiLocationEventMark(JavaThread *thread, const methodHandle& method, address location) :
 222     JvmtiMethodEventMark(thread, method),
 223     _loc(location - method->code_base()) {};
 224   jlocation location() { return _loc; }
 225 };
 226 
 227 class JvmtiExceptionEventMark : public JvmtiLocationEventMark {
 228 private:
 229   jobject _exc;
 230 
 231 public:
 232   JvmtiExceptionEventMark(JavaThread *thread, const methodHandle& method, address location, Handle exception) :
 233     JvmtiLocationEventMark(thread, method, location),
 234     _exc(to_jobject(exception())) {};
 235   jobject exception() { return _exc; }
 236 };
 237 
 238 class JvmtiClassFileLoadEventMark : public JvmtiThreadEventMark {
 239 private:
 240   const char *_class_name;
 241   jobject _jloader;
 242   jobject _protection_domain;
 243   jclass  _class_being_redefined;
 244 
 245 public:
 246   JvmtiClassFileLoadEventMark(JavaThread *thread, Symbol* name,
 247      Handle class_loader, Handle prot_domain, Klass* class_being_redefined) : JvmtiThreadEventMark(thread) {
 248       _class_name = name != NULL? name->as_utf8() : NULL;
 249       _jloader = (jobject)to_jobject(class_loader());
 250       _protection_domain = (jobject)to_jobject(prot_domain());
 251       if (class_being_redefined == NULL) {
 252         _class_being_redefined = NULL;
 253       } else {
 254         _class_being_redefined = (jclass)to_jclass(class_being_redefined);
 255       }
 256   };
 257   const char *class_name() {
 258     return _class_name;
 259   }
 260   jobject jloader() {
 261     return _jloader;
 262   }
 263   jobject protection_domain() {
 264     return _protection_domain;
 265   }
 266   jclass class_being_redefined() {
 267     return _class_being_redefined;
 268   }
 269 };
 270 
 271 //////////////////////////////////////////////////////////////////////////////
 272 
 273 int               JvmtiExport::_field_access_count                        = 0;
 274 int               JvmtiExport::_field_modification_count                  = 0;
 275 
 276 bool              JvmtiExport::_can_access_local_variables                = false;
 277 bool              JvmtiExport::_can_hotswap_or_post_breakpoint            = false;
 278 bool              JvmtiExport::_can_modify_any_class                      = false;
 279 bool              JvmtiExport::_can_walk_any_space                        = false;
 280 
 281 uint64_t          JvmtiExport::_redefinition_count                        = 0;
 282 bool              JvmtiExport::_all_dependencies_are_recorded             = false;
 283 
 284 //
 285 // field access management
 286 //
 287 
 288 // interpreter generator needs the address of the counter
 289 address JvmtiExport::get_field_access_count_addr() {
 290   // We don't grab a lock because we don't want to
 291   // serialize field access between all threads. This means that a
 292   // thread on another processor can see the wrong count value and
 293   // may either miss making a needed call into post_field_access()
 294   // or will make an unneeded call into post_field_access(). We pay
 295   // this price to avoid slowing down the VM when we aren't watching
 296   // field accesses.
 297   // Other access/mutation safe by virtue of being in VM state.
 298   return (address)(&_field_access_count);
 299 }
 300 
 301 //
 302 // field modification management
 303 //
 304 
 305 // interpreter generator needs the address of the counter
 306 address JvmtiExport::get_field_modification_count_addr() {
 307   // We don't grab a lock because we don't
 308   // want to serialize field modification between all threads. This
 309   // means that a thread on another processor can see the wrong
 310   // count value and may either miss making a needed call into
 311   // post_field_modification() or will make an unneeded call into
 312   // post_field_modification(). We pay this price to avoid slowing
 313   // down the VM when we aren't watching field modifications.
 314   // Other access/mutation safe by virtue of being in VM state.
 315   return (address)(&_field_modification_count);
 316 }
 317 
 318 
 319 ///////////////////////////////////////////////////////////////
 320 // Functions needed by java.lang.instrument for starting up javaagent.
 321 ///////////////////////////////////////////////////////////////
 322 
 323 jint
 324 JvmtiExport::get_jvmti_interface(JavaVM *jvm, void **penv, jint version) {
 325   // The JVMTI_VERSION_INTERFACE_JVMTI part of the version number
 326   // has already been validated in JNI GetEnv().
 327   int major, minor, micro;
 328 
 329   // micro version doesn't matter here (yet?)
 330   decode_version_values(version, &major, &minor, &micro);
 331   switch (major) {
 332     case 1:
 333       switch (minor) {
 334         case 0:  // version 1.0.<micro> is recognized
 335         case 1:  // version 1.1.<micro> is recognized
 336         case 2:  // version 1.2.<micro> is recognized
 337           break;
 338 
 339         default:
 340           return JNI_EVERSION;  // unsupported minor version number
 341       }
 342       break;
 343     case 9:
 344       switch (minor) {
 345         case 0:  // version 9.0.<micro> is recognized
 346           break;
 347         default:
 348           return JNI_EVERSION;  // unsupported minor version number
 349       }
 350       break;
 351     case 11:
 352       switch (minor) {
 353         case 0:  // version 11.0.<micro> is recognized
 354           break;
 355         default:
 356           return JNI_EVERSION;  // unsupported minor version number
 357       }
 358       break;
 359     default:
 360       // Starting from 13 we do not care about minor version anymore
 361       if (major < 13 || major > Abstract_VM_Version::vm_major_version()) {
 362         return JNI_EVERSION;  // unsupported major version number
 363       }
 364   }
 365 
 366   if (JvmtiEnv::get_phase() == JVMTI_PHASE_LIVE) {
 367     JavaThread* current_thread = JavaThread::current();
 368     // transition code: native to VM
 369     ThreadInVMfromNative __tiv(current_thread);
 370     VM_ENTRY_BASE(jvmtiEnv*, JvmtiExport::get_jvmti_interface, current_thread)
 371     debug_only(VMNativeEntryWrapper __vew;)
 372 
 373     JvmtiEnv *jvmti_env = JvmtiEnv::create_a_jvmti(version);
 374     *penv = jvmti_env->jvmti_external();  // actual type is jvmtiEnv* -- not to be confused with JvmtiEnv*
 375     return JNI_OK;
 376 
 377   } else if (JvmtiEnv::get_phase() == JVMTI_PHASE_ONLOAD) {
 378     // not live, no thread to transition
 379     JvmtiEnv *jvmti_env = JvmtiEnv::create_a_jvmti(version);
 380     *penv = jvmti_env->jvmti_external();  // actual type is jvmtiEnv* -- not to be confused with JvmtiEnv*
 381     return JNI_OK;
 382 
 383   } else {
 384     // Called at the wrong time
 385     *penv = NULL;
 386     return JNI_EDETACHED;
 387   }
 388 }
 389 
 390 void
 391 JvmtiExport::add_default_read_edges(Handle h_module, TRAPS) {
 392   if (!Universe::is_module_initialized()) {
 393     return; // extra safety
 394   }
 395   assert(!h_module.is_null(), "module should always be set");
 396 
 397   // Invoke the transformedByAgent method
 398   JavaValue result(T_VOID);
 399   JavaCalls::call_static(&result,
 400                          vmClasses::module_Modules_klass(),
 401                          vmSymbols::transformedByAgent_name(),
 402                          vmSymbols::transformedByAgent_signature(),
 403                          h_module,
 404                          THREAD);
 405 
 406   if (HAS_PENDING_EXCEPTION) {
 407     LogTarget(Trace, jvmti) log;
 408     LogStream log_stream(log);
 409     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 410     log_stream.cr();
 411     CLEAR_PENDING_EXCEPTION;
 412     return;
 413   }
 414 }
 415 
 416 jvmtiError
 417 JvmtiExport::add_module_reads(Handle module, Handle to_module, TRAPS) {
 418   if (!Universe::is_module_initialized()) {
 419     return JVMTI_ERROR_NONE; // extra safety
 420   }
 421   assert(!module.is_null(), "module should always be set");
 422   assert(!to_module.is_null(), "to_module should always be set");
 423 
 424   // Invoke the addReads method
 425   JavaValue result(T_VOID);
 426   JavaCalls::call_static(&result,
 427                          vmClasses::module_Modules_klass(),
 428                          vmSymbols::addReads_name(),
 429                          vmSymbols::addReads_signature(),
 430                          module,
 431                          to_module,
 432                          THREAD);
 433 
 434   if (HAS_PENDING_EXCEPTION) {
 435     LogTarget(Trace, jvmti) log;
 436     LogStream log_stream(log);
 437     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 438     log_stream.cr();
 439     CLEAR_PENDING_EXCEPTION;
 440     return JVMTI_ERROR_INTERNAL;
 441   }
 442   return JVMTI_ERROR_NONE;
 443 }
 444 
 445 jvmtiError
 446 JvmtiExport::add_module_exports(Handle module, Handle pkg_name, Handle to_module, TRAPS) {
 447   if (!Universe::is_module_initialized()) {
 448     return JVMTI_ERROR_NONE; // extra safety
 449   }
 450   assert(!module.is_null(), "module should always be set");
 451   assert(!to_module.is_null(), "to_module should always be set");
 452   assert(!pkg_name.is_null(), "pkg_name should always be set");
 453 
 454   // Invoke the addExports method
 455   JavaValue result(T_VOID);
 456   JavaCalls::call_static(&result,
 457                          vmClasses::module_Modules_klass(),
 458                          vmSymbols::addExports_name(),
 459                          vmSymbols::addExports_signature(),
 460                          module,
 461                          pkg_name,
 462                          to_module,
 463                          THREAD);
 464 
 465   if (HAS_PENDING_EXCEPTION) {
 466     Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
 467     LogTarget(Trace, jvmti) log;
 468     LogStream log_stream(log);
 469     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 470     log_stream.cr();
 471     CLEAR_PENDING_EXCEPTION;
 472     if (ex_name == vmSymbols::java_lang_IllegalArgumentException()) {
 473       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 474     }
 475     return JVMTI_ERROR_INTERNAL;
 476   }
 477   return JVMTI_ERROR_NONE;
 478 }
 479 
 480 jvmtiError
 481 JvmtiExport::add_module_opens(Handle module, Handle pkg_name, Handle to_module, TRAPS) {
 482   if (!Universe::is_module_initialized()) {
 483     return JVMTI_ERROR_NONE; // extra safety
 484   }
 485   assert(!module.is_null(), "module should always be set");
 486   assert(!to_module.is_null(), "to_module should always be set");
 487   assert(!pkg_name.is_null(), "pkg_name should always be set");
 488 
 489   // Invoke the addOpens method
 490   JavaValue result(T_VOID);
 491   JavaCalls::call_static(&result,
 492                          vmClasses::module_Modules_klass(),
 493                          vmSymbols::addOpens_name(),
 494                          vmSymbols::addExports_signature(),
 495                          module,
 496                          pkg_name,
 497                          to_module,
 498                          THREAD);
 499 
 500   if (HAS_PENDING_EXCEPTION) {
 501     Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
 502     LogTarget(Trace, jvmti) log;
 503     LogStream log_stream(log);
 504     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 505     log_stream.cr();
 506     CLEAR_PENDING_EXCEPTION;
 507     if (ex_name == vmSymbols::java_lang_IllegalArgumentException()) {
 508       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 509     }
 510     return JVMTI_ERROR_INTERNAL;
 511   }
 512   return JVMTI_ERROR_NONE;
 513 }
 514 
 515 jvmtiError
 516 JvmtiExport::add_module_uses(Handle module, Handle service, TRAPS) {
 517   if (!Universe::is_module_initialized()) {
 518     return JVMTI_ERROR_NONE; // extra safety
 519   }
 520   assert(!module.is_null(), "module should always be set");
 521   assert(!service.is_null(), "service should always be set");
 522 
 523   // Invoke the addUses method
 524   JavaValue result(T_VOID);
 525   JavaCalls::call_static(&result,
 526                          vmClasses::module_Modules_klass(),
 527                          vmSymbols::addUses_name(),
 528                          vmSymbols::addUses_signature(),
 529                          module,
 530                          service,
 531                          THREAD);
 532 
 533   if (HAS_PENDING_EXCEPTION) {
 534     LogTarget(Trace, jvmti) log;
 535     LogStream log_stream(log);
 536     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 537     log_stream.cr();
 538     CLEAR_PENDING_EXCEPTION;
 539     return JVMTI_ERROR_INTERNAL;
 540   }
 541   return JVMTI_ERROR_NONE;
 542 }
 543 
 544 jvmtiError
 545 JvmtiExport::add_module_provides(Handle module, Handle service, Handle impl_class, TRAPS) {
 546   if (!Universe::is_module_initialized()) {
 547     return JVMTI_ERROR_NONE; // extra safety
 548   }
 549   assert(!module.is_null(), "module should always be set");
 550   assert(!service.is_null(), "service should always be set");
 551   assert(!impl_class.is_null(), "impl_class should always be set");
 552 
 553   // Invoke the addProvides method
 554   JavaValue result(T_VOID);
 555   JavaCalls::call_static(&result,
 556                          vmClasses::module_Modules_klass(),
 557                          vmSymbols::addProvides_name(),
 558                          vmSymbols::addProvides_signature(),
 559                          module,
 560                          service,
 561                          impl_class,
 562                          THREAD);
 563 
 564   if (HAS_PENDING_EXCEPTION) {
 565     LogTarget(Trace, jvmti) log;
 566     LogStream log_stream(log);
 567     java_lang_Throwable::print(PENDING_EXCEPTION, &log_stream);
 568     log_stream.cr();
 569     CLEAR_PENDING_EXCEPTION;
 570     return JVMTI_ERROR_INTERNAL;
 571   }
 572   return JVMTI_ERROR_NONE;
 573 }
 574 
 575 void
 576 JvmtiExport::decode_version_values(jint version, int * major, int * minor,
 577                                    int * micro) {
 578   *major = (version & JVMTI_VERSION_MASK_MAJOR) >> JVMTI_VERSION_SHIFT_MAJOR;
 579   *minor = (version & JVMTI_VERSION_MASK_MINOR) >> JVMTI_VERSION_SHIFT_MINOR;
 580   *micro = (version & JVMTI_VERSION_MASK_MICRO) >> JVMTI_VERSION_SHIFT_MICRO;
 581 }
 582 
 583 void JvmtiExport::enter_primordial_phase() {
 584   JvmtiEnvBase::set_phase(JVMTI_PHASE_PRIMORDIAL);
 585 }
 586 
 587 void JvmtiExport::enter_early_start_phase() {
 588   set_early_vmstart_recorded(true);
 589 }
 590 
 591 void JvmtiExport::enter_start_phase() {
 592   JvmtiEnvBase::set_phase(JVMTI_PHASE_START);
 593 }
 594 
 595 void JvmtiExport::enter_onload_phase() {
 596   JvmtiEnvBase::set_phase(JVMTI_PHASE_ONLOAD);
 597 }
 598 
 599 void JvmtiExport::enter_live_phase() {
 600   JvmtiEnvBase::set_phase(JVMTI_PHASE_LIVE);
 601 }
 602 
 603 //
 604 // JVMTI events that the VM posts to the debugger and also startup agent
 605 // and call the agent's premain() for java.lang.instrument.
 606 //
 607 
 608 void JvmtiExport::post_early_vm_start() {
 609   EVT_TRIG_TRACE(JVMTI_EVENT_VM_START, ("Trg Early VM start event triggered" ));
 610 
 611   // can now enable some events
 612   JvmtiEventController::vm_start();
 613 
 614   JvmtiEnvIterator it;
 615   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 616     // Only early vmstart envs post early VMStart event
 617     if (env->early_vmstart_env() && env->is_enabled(JVMTI_EVENT_VM_START)) {
 618       EVT_TRACE(JVMTI_EVENT_VM_START, ("Evt Early VM start event sent" ));
 619       JavaThread *thread  = JavaThread::current();
 620       JvmtiThreadEventMark jem(thread);
 621       JvmtiJavaThreadEventTransition jet(thread);
 622       jvmtiEventVMStart callback = env->callbacks()->VMStart;
 623       if (callback != NULL) {
 624         (*callback)(env->jvmti_external(), jem.jni_env());
 625       }
 626     }
 627   }
 628 }
 629 
 630 void JvmtiExport::post_vm_start() {
 631   EVT_TRIG_TRACE(JVMTI_EVENT_VM_START, ("Trg VM start event triggered" ));
 632 
 633   // can now enable some events
 634   JvmtiEventController::vm_start();
 635 
 636   JvmtiEnvIterator it;
 637   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 638     // Early vmstart envs do not post normal VMStart event
 639     if (!env->early_vmstart_env() && env->is_enabled(JVMTI_EVENT_VM_START)) {
 640       EVT_TRACE(JVMTI_EVENT_VM_START, ("Evt VM start event sent" ));
 641 
 642       JavaThread *thread  = JavaThread::current();
 643       JvmtiThreadEventMark jem(thread);
 644       JvmtiJavaThreadEventTransition jet(thread);
 645       jvmtiEventVMStart callback = env->callbacks()->VMStart;
 646       if (callback != NULL) {
 647         (*callback)(env->jvmti_external(), jem.jni_env());
 648       }
 649     }
 650   }
 651 }
 652 
 653 static OopStorage* _jvmti_oop_storage = NULL;
 654 static OopStorage* _weak_tag_storage = NULL;
 655 
 656 OopStorage* JvmtiExport::jvmti_oop_storage() {
 657   assert(_jvmti_oop_storage != NULL, "not yet initialized");
 658   return _jvmti_oop_storage;
 659 }
 660 
 661 OopStorage* JvmtiExport::weak_tag_storage() {
 662   assert(_weak_tag_storage != NULL, "not yet initialized");
 663   return _weak_tag_storage;
 664 }
 665 
 666 void JvmtiExport::initialize_oop_storage() {
 667   // OopStorage needs to be created early in startup and unconditionally
 668   // because of OopStorageSet static array indices.
 669   _jvmti_oop_storage = OopStorageSet::create_strong("JVMTI OopStorage", mtServiceability);
 670   _weak_tag_storage  = OopStorageSet::create_weak("JVMTI Tag Weak OopStorage", mtServiceability);
 671   _weak_tag_storage->register_num_dead_callback(&JvmtiTagMap::gc_notification);
 672 }
 673 
 674 void JvmtiExport::post_vm_initialized() {
 675   EVT_TRIG_TRACE(JVMTI_EVENT_VM_INIT, ("Trg VM init event triggered" ));
 676 
 677   // can now enable events
 678   JvmtiEventController::vm_init();
 679 
 680   JvmtiEnvIterator it;
 681   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 682     if (env->is_enabled(JVMTI_EVENT_VM_INIT)) {
 683       EVT_TRACE(JVMTI_EVENT_VM_INIT, ("Evt VM init event sent" ));
 684 
 685       JavaThread *thread  = JavaThread::current();
 686       JvmtiThreadEventMark jem(thread);
 687       JvmtiJavaThreadEventTransition jet(thread);
 688       jvmtiEventVMInit callback = env->callbacks()->VMInit;
 689       if (callback != NULL) {
 690         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
 691       }
 692     }
 693   }
 694 }
 695 
 696 
 697 void JvmtiExport::post_vm_death() {
 698   EVT_TRIG_TRACE(JVMTI_EVENT_VM_DEATH, ("Trg VM death event triggered" ));
 699 
 700   JvmtiEnvIterator it;
 701   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 702     if (env->is_enabled(JVMTI_EVENT_VM_DEATH)) {
 703       EVT_TRACE(JVMTI_EVENT_VM_DEATH, ("Evt VM death event sent" ));
 704 
 705       JavaThread *thread  = JavaThread::current();
 706       JvmtiEventMark jem(thread);
 707       JvmtiJavaThreadEventTransition jet(thread);
 708       jvmtiEventVMDeath callback = env->callbacks()->VMDeath;
 709       if (callback != NULL) {
 710         (*callback)(env->jvmti_external(), jem.jni_env());
 711       }
 712     }
 713   }
 714 
 715   JvmtiEnvBase::set_phase(JVMTI_PHASE_DEAD);
 716   JvmtiEventController::vm_death();
 717 }
 718 
 719 char**
 720 JvmtiExport::get_all_native_method_prefixes(int* count_ptr) {
 721   // Have to grab JVMTI thread state lock to be sure environment doesn't
 722   // go away while we iterate them.  No locks during VM bring-up.
 723   if (Threads::number_of_threads() == 0 || SafepointSynchronize::is_at_safepoint()) {
 724     return JvmtiEnvBase::get_all_native_method_prefixes(count_ptr);
 725   } else {
 726     MutexLocker mu(JvmtiThreadState_lock);
 727     return JvmtiEnvBase::get_all_native_method_prefixes(count_ptr);
 728   }
 729 }
 730 
 731 // Convert an external thread reference to a JavaThread found on the
 732 // specified ThreadsList. The ThreadsListHandle in the caller "protects"
 733 // the returned JavaThread *.
 734 //
 735 // If thread_oop_p is not NULL, then the caller wants to use the oop
 736 // after this call so the oop is returned. On success, *jt_pp is set
 737 // to the converted JavaThread * and JVMTI_ERROR_NONE is returned.
 738 // On error, returns various JVMTI_ERROR_* values.
 739 //
 740 jvmtiError
 741 JvmtiExport::cv_external_thread_to_JavaThread(ThreadsList * t_list,
 742                                               jthread thread,
 743                                               JavaThread ** jt_pp,
 744                                               oop * thread_oop_p) {
 745   assert(t_list != NULL, "must have a ThreadsList");
 746   assert(jt_pp != NULL, "must have a return JavaThread pointer");
 747   // thread_oop_p is optional so no assert()
 748 
 749   oop thread_oop = JNIHandles::resolve_external_guard(thread);
 750   if (thread_oop == NULL) {
 751     // NULL jthread, GC'ed jthread or a bad JNI handle.
 752     return JVMTI_ERROR_INVALID_THREAD;
 753   }
 754   // Looks like an oop at this point.
 755 
 756   if (!thread_oop->is_a(vmClasses::Thread_klass())) {
 757     // The oop is not a java.lang.Thread.



 758     return JVMTI_ERROR_INVALID_THREAD;
 759   }
 760   // Looks like a java.lang.Thread oop at this point.
 761 
 762   if (thread_oop_p != NULL) {
 763     // Return the oop to the caller; the caller may still want
 764     // the oop even if this function returns an error.
 765     *thread_oop_p = thread_oop;
 766   }
 767 
 768   JavaThread * java_thread = java_lang_Thread::thread(thread_oop);
 769   if (java_thread == NULL) {



 770     // The java.lang.Thread does not contain a JavaThread * so it has
 771     // not yet run or it has died.
 772     return JVMTI_ERROR_THREAD_NOT_ALIVE;
 773   }
 774   // Looks like a live JavaThread at this point.
 775 
 776   // We do not check the EnableThreadSMRExtraValidityChecks option
 777   // for this includes() call because JVM/TI's spec is tighter.
 778   if (!t_list->includes(java_thread)) {
 779     // Not on the JavaThreads list so it is not alive.
 780     return JVMTI_ERROR_THREAD_NOT_ALIVE;
 781   }
 782 
 783   // Return a live JavaThread that is "protected" by the
 784   // ThreadsListHandle in the caller.
 785   *jt_pp = java_thread;
 786 
 787   return JVMTI_ERROR_NONE;
 788 }
 789 
 790 // Convert an oop to a JavaThread found on the specified ThreadsList.
 791 // The ThreadsListHandle in the caller "protects" the returned
 792 // JavaThread *.
 793 //
 794 // On success, *jt_pp is set to the converted JavaThread * and
 795 // JVMTI_ERROR_NONE is returned. On error, returns various
 796 // JVMTI_ERROR_* values.
 797 //
 798 jvmtiError
 799 JvmtiExport::cv_oop_to_JavaThread(ThreadsList * t_list, oop thread_oop,
 800                                   JavaThread ** jt_pp) {
 801   assert(t_list != NULL, "must have a ThreadsList");
 802   assert(thread_oop != NULL, "must have an oop");
 803   assert(jt_pp != NULL, "must have a return JavaThread pointer");
 804 
 805   if (!thread_oop->is_a(vmClasses::Thread_klass())) {
 806     // The oop is not a java.lang.Thread.
 807     return JVMTI_ERROR_INVALID_THREAD;
 808   }
 809   // Looks like a java.lang.Thread oop at this point.
 810 
 811   JavaThread * java_thread = java_lang_Thread::thread(thread_oop);
 812   if (java_thread == NULL) {
 813     // The java.lang.Thread does not contain a JavaThread * so it has
 814     // not yet run or it has died.
 815     return JVMTI_ERROR_THREAD_NOT_ALIVE;
 816   }
 817   // Looks like a live JavaThread at this point.
 818 
 819   // We do not check the EnableThreadSMRExtraValidityChecks option
 820   // for this includes() call because JVM/TI's spec is tighter.
 821   if (!t_list->includes(java_thread)) {
 822     // Not on the JavaThreads list so it is not alive.
 823     return JVMTI_ERROR_THREAD_NOT_ALIVE;
 824   }
 825 
 826   // Return a live JavaThread that is "protected" by the
 827   // ThreadsListHandle in the caller.
 828   *jt_pp = java_thread;
 829 
 830   return JVMTI_ERROR_NONE;
 831 }
 832 
 833 class JvmtiClassFileLoadHookPoster : public StackObj {
 834  private:
 835   Symbol*            _h_name;
 836   Handle               _class_loader;
 837   Handle               _h_protection_domain;
 838   unsigned char **     _data_ptr;
 839   unsigned char **     _end_ptr;
 840   JavaThread *         _thread;
 841   jint                 _curr_len;
 842   unsigned char *      _curr_data;
 843   JvmtiEnv *           _curr_env;
 844   JvmtiCachedClassFileData ** _cached_class_file_ptr;
 845   JvmtiThreadState *   _state;
 846   Klass*               _class_being_redefined;
 847   JvmtiClassLoadKind   _load_kind;
 848   bool                 _has_been_modified;
 849 
 850  public:
 851   inline JvmtiClassFileLoadHookPoster(Symbol* h_name, Handle class_loader,
 852                                       Handle h_protection_domain,
 853                                       unsigned char **data_ptr, unsigned char **end_ptr,
 854                                       JvmtiCachedClassFileData **cache_ptr) {
 855     _h_name = h_name;
 856     _class_loader = class_loader;
 857     _h_protection_domain = h_protection_domain;
 858     _data_ptr = data_ptr;
 859     _end_ptr = end_ptr;
 860     _thread = JavaThread::current();
 861     _curr_len = *end_ptr - *data_ptr;
 862     _curr_data = *data_ptr;
 863     _curr_env = NULL;
 864     _cached_class_file_ptr = cache_ptr;
 865     _has_been_modified = false;
 866 
 867     _state = _thread->jvmti_thread_state();
 868     if (_state != NULL) {
 869       _class_being_redefined = _state->get_class_being_redefined();
 870       _load_kind = _state->get_class_load_kind();
 871       Klass* klass = (_class_being_redefined == NULL) ? NULL : _class_being_redefined;
 872       if (_load_kind != jvmti_class_load_kind_load && klass != NULL) {
 873         ModuleEntry* module_entry = InstanceKlass::cast(klass)->module();
 874         assert(module_entry != NULL, "module_entry should always be set");
 875         if (module_entry->is_named() &&
 876             module_entry->module() != NULL &&
 877             !module_entry->has_default_read_edges()) {
 878           if (!module_entry->set_has_default_read_edges()) {
 879             // We won a potential race.
 880             // Add read edges to the unnamed modules of the bootstrap and app class loaders
 881             Handle class_module(_thread, module_entry->module()); // Obtain j.l.r.Module
 882             JvmtiExport::add_default_read_edges(class_module, _thread);
 883           }
 884         }
 885       }
 886       // Clear class_being_redefined flag here. The action
 887       // from agent handler could generate a new class file load
 888       // hook event and if it is not cleared the new event generated
 889       // from regular class file load could have this stale redefined
 890       // class handle info.
 891       _state->clear_class_being_redefined();
 892     } else {
 893       // redefine and retransform will always set the thread state
 894       _class_being_redefined = NULL;
 895       _load_kind = jvmti_class_load_kind_load;
 896     }
 897   }
 898 
 899   void post() {
 900     post_all_envs();
 901     copy_modified_data();
 902   }
 903 
 904   bool has_been_modified() { return _has_been_modified; }
 905 
 906  private:
 907   void post_all_envs() {
 908     if (_load_kind != jvmti_class_load_kind_retransform) {
 909       // for class load and redefine,
 910       // call the non-retransformable agents
 911       JvmtiEnvIterator it;
 912       for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 913         if (!env->is_retransformable() && env->is_enabled(JVMTI_EVENT_CLASS_FILE_LOAD_HOOK)) {
 914           // non-retransformable agents cannot retransform back,
 915           // so no need to cache the original class file bytes
 916           post_to_env(env, false);
 917         }
 918       }
 919     }
 920     JvmtiEnvIterator it;
 921     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
 922       // retransformable agents get all events
 923       if (env->is_retransformable() && env->is_enabled(JVMTI_EVENT_CLASS_FILE_LOAD_HOOK)) {
 924         // retransformable agents need to cache the original class file
 925         // bytes if changes are made via the ClassFileLoadHook
 926         post_to_env(env, true);
 927       }
 928     }
 929   }
 930 
 931   void post_to_env(JvmtiEnv* env, bool caching_needed) {
 932     if (env->phase() == JVMTI_PHASE_PRIMORDIAL && !env->early_class_hook_env()) {
 933       return;
 934     }
 935     unsigned char *new_data = NULL;
 936     jint new_len = 0;
 937     JvmtiClassFileLoadEventMark jem(_thread, _h_name, _class_loader,
 938                                     _h_protection_domain,
 939                                     _class_being_redefined);
 940     JvmtiJavaThreadEventTransition jet(_thread);
 941     jvmtiEventClassFileLoadHook callback = env->callbacks()->ClassFileLoadHook;
 942     if (callback != NULL) {
 943       (*callback)(env->jvmti_external(), jem.jni_env(),
 944                   jem.class_being_redefined(),
 945                   jem.jloader(), jem.class_name(),
 946                   jem.protection_domain(),
 947                   _curr_len, _curr_data,
 948                   &new_len, &new_data);
 949     }
 950     if (new_data != NULL) {
 951       // this agent has modified class data.
 952       _has_been_modified = true;
 953       if (caching_needed && *_cached_class_file_ptr == NULL) {
 954         // data has been changed by the new retransformable agent
 955         // and it hasn't already been cached, cache it
 956         JvmtiCachedClassFileData *p;
 957         p = (JvmtiCachedClassFileData *)os::malloc(
 958           offset_of(JvmtiCachedClassFileData, data) + _curr_len, mtInternal);
 959         if (p == NULL) {
 960           vm_exit_out_of_memory(offset_of(JvmtiCachedClassFileData, data) + _curr_len,
 961             OOM_MALLOC_ERROR,
 962             "unable to allocate cached copy of original class bytes");
 963         }
 964         p->length = _curr_len;
 965         memcpy(p->data, _curr_data, _curr_len);
 966         *_cached_class_file_ptr = p;
 967       }
 968 
 969       if (_curr_data != *_data_ptr) {
 970         // curr_data is previous agent modified class data.
 971         // And this has been changed by the new agent so
 972         // we can delete it now.
 973         _curr_env->Deallocate(_curr_data);
 974       }
 975 
 976       // Class file data has changed by the current agent.
 977       _curr_data = new_data;
 978       _curr_len = new_len;
 979       // Save the current agent env we need this to deallocate the
 980       // memory allocated by this agent.
 981       _curr_env = env;
 982     }
 983   }
 984 
 985   void copy_modified_data() {
 986     // if one of the agent has modified class file data.
 987     // Copy modified class data to new resources array.
 988     if (_curr_data != *_data_ptr) {
 989       *_data_ptr = NEW_RESOURCE_ARRAY(u1, _curr_len);
 990       memcpy(*_data_ptr, _curr_data, _curr_len);
 991       *_end_ptr = *_data_ptr + _curr_len;
 992       _curr_env->Deallocate(_curr_data);
 993     }
 994   }
 995 };
 996 
 997 bool JvmtiExport::is_early_phase() {
 998   return JvmtiEnvBase::get_phase() <= JVMTI_PHASE_PRIMORDIAL;
 999 }
1000 
1001 bool JvmtiExport::has_early_class_hook_env() {
1002   JvmtiEnvIterator it;
1003   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1004     if (env->early_class_hook_env()) {
1005       return true;
1006     }
1007   }
1008   return false;
1009 }
1010 
1011 bool JvmtiExport::_should_post_class_file_load_hook = false;
1012 
1013 // this entry is for class file load hook on class load, redefine and retransform
1014 bool JvmtiExport::post_class_file_load_hook(Symbol* h_name,
1015                                             Handle class_loader,
1016                                             Handle h_protection_domain,
1017                                             unsigned char **data_ptr,
1018                                             unsigned char **end_ptr,
1019                                             JvmtiCachedClassFileData **cache_ptr) {
1020   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1021     return false;
1022   }
1023 
1024   JvmtiClassFileLoadHookPoster poster(h_name, class_loader,
1025                                       h_protection_domain,
1026                                       data_ptr, end_ptr,
1027                                       cache_ptr);
1028   poster.post();
1029   return poster.has_been_modified();
1030 }
1031 
1032 void JvmtiExport::report_unsupported(bool on) {
1033   // If any JVMTI service is turned on, we need to exit before native code
1034   // tries to access nonexistant services.
1035   if (on) {
1036     vm_exit_during_initialization("Java Kernel does not support JVMTI.");
1037   }
1038 }
1039 
1040 
1041 static inline Klass* oop_to_klass(oop obj) {
1042   Klass* k = obj->klass();
1043 
1044   // if the object is a java.lang.Class then return the java mirror
1045   if (k == vmClasses::Class_klass()) {
1046     if (!java_lang_Class::is_primitive(obj)) {
1047       k = java_lang_Class::as_Klass(obj);
1048       assert(k != NULL, "class for non-primitive mirror must exist");
1049     }
1050   }
1051   return k;
1052 }
1053 
1054 class JvmtiObjectAllocEventMark : public JvmtiClassEventMark  {
1055  private:
1056    jobject _jobj;
1057    jlong    _size;
1058  public:
1059    JvmtiObjectAllocEventMark(JavaThread *thread, oop obj) : JvmtiClassEventMark(thread, oop_to_klass(obj)) {
1060      _jobj = (jobject)to_jobject(obj);
1061      _size = obj->size() * wordSize;
1062    };
1063    jobject jni_jobject() { return _jobj; }
1064    jlong size() { return _size; }
1065 };
1066 
1067 class JvmtiCompiledMethodLoadEventMark : public JvmtiMethodEventMark {
1068  private:
1069   jint _code_size;
1070   const void *_code_data;
1071   jint _map_length;
1072   jvmtiAddrLocationMap *_map;
1073   const void *_compile_info;
1074  public:
1075   JvmtiCompiledMethodLoadEventMark(JavaThread *thread, nmethod *nm, void* compile_info_ptr = NULL)
1076           : JvmtiMethodEventMark(thread,methodHandle(thread, nm->method())) {
1077     _code_data = nm->code_begin();
1078     _code_size = nm->code_size();
1079     _compile_info = compile_info_ptr; // Set void pointer of compiledMethodLoad Event. Default value is NULL.
1080     JvmtiCodeBlobEvents::build_jvmti_addr_location_map(nm, &_map, &_map_length);
1081   }
1082   ~JvmtiCompiledMethodLoadEventMark() {
1083      FREE_C_HEAP_ARRAY(jvmtiAddrLocationMap, _map);
1084   }
1085 
1086   jint code_size() { return _code_size; }
1087   const void *code_data() { return _code_data; }
1088   jint map_length() { return _map_length; }
1089   const jvmtiAddrLocationMap* map() { return _map; }
1090   const void *compile_info() { return _compile_info; }
1091 };
1092 
1093 
1094 
1095 class JvmtiMonitorEventMark : public JvmtiThreadEventMark {
1096 private:
1097   jobject _jobj;
1098 public:
1099   JvmtiMonitorEventMark(JavaThread *thread, oop object)
1100           : JvmtiThreadEventMark(thread){
1101      _jobj = to_jobject(object);
1102   }
1103   jobject jni_object() { return _jobj; }
1104 };
1105 
1106 ///////////////////////////////////////////////////////////////
1107 //
1108 // pending CompiledMethodUnload support
1109 //
1110 
1111 void JvmtiExport::post_compiled_method_unload(
1112        jmethodID method, const void *code_begin) {
1113   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1114     return;
1115   }
1116   JavaThread* thread = JavaThread::current();
1117   EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_UNLOAD,
1118                  ("[%s] method compile unload event triggered",
1119                   JvmtiTrace::safe_get_thread_name(thread)));
1120 
1121   // post the event for each environment that has this event enabled.
1122   JvmtiEnvIterator it;
1123   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1124     if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_UNLOAD)) {
1125       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1126         continue;
1127       }
1128       EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_UNLOAD,
1129                 ("[%s] class compile method unload event sent jmethodID " PTR_FORMAT,
1130                  JvmtiTrace::safe_get_thread_name(thread), p2i(method)));
1131 
1132       ResourceMark rm(thread);
1133 
1134       JvmtiEventMark jem(thread);
1135       JvmtiJavaThreadEventTransition jet(thread);
1136       jvmtiEventCompiledMethodUnload callback = env->callbacks()->CompiledMethodUnload;
1137       if (callback != NULL) {
1138         (*callback)(env->jvmti_external(), method, code_begin);
1139       }
1140     }
1141   }
1142 }
1143 
1144 ///////////////////////////////////////////////////////////////
1145 //
1146 // JvmtiExport
1147 //
1148 
1149 void JvmtiExport::post_raw_breakpoint(JavaThread *thread, Method* method, address location) {
1150   HandleMark hm(thread);
1151   methodHandle mh(thread, method);
1152 
1153   JvmtiThreadState *state = thread->jvmti_thread_state();
1154   if (state == NULL) {
1155     return;
1156   }




1157   EVT_TRIG_TRACE(JVMTI_EVENT_BREAKPOINT, ("[%s] Trg Breakpoint triggered",
1158                       JvmtiTrace::safe_get_thread_name(thread)));
1159   JvmtiEnvThreadStateIterator it(state);
1160   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1161     ets->compare_and_set_current_location(mh(), location, JVMTI_EVENT_BREAKPOINT);
1162     if (!ets->breakpoint_posted() && ets->is_enabled(JVMTI_EVENT_BREAKPOINT)) {
1163       ThreadState old_os_state = thread->osthread()->get_state();
1164       thread->osthread()->set_state(BREAKPOINTED);
1165       EVT_TRACE(JVMTI_EVENT_BREAKPOINT, ("[%s] Evt Breakpoint sent %s.%s @ " INTX_FORMAT,
1166                      JvmtiTrace::safe_get_thread_name(thread),
1167                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1168                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1169                      location - mh()->code_base() ));
1170 
1171       JvmtiEnv *env = ets->get_env();
1172       JvmtiLocationEventMark jem(thread, mh, location);
1173       JvmtiJavaThreadEventTransition jet(thread);
1174       jvmtiEventBreakpoint callback = env->callbacks()->Breakpoint;
1175       if (callback != NULL) {
1176         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1177                     jem.jni_methodID(), jem.location());
1178       }
1179 
1180       ets->set_breakpoint_posted();
1181       thread->osthread()->set_state(old_os_state);
1182     }
1183   }
1184 }
1185 
1186 //////////////////////////////////////////////////////////////////////////////
1187 
1188 bool              JvmtiExport::_can_get_source_debug_extension            = false;
1189 bool              JvmtiExport::_can_maintain_original_method_order        = false;
1190 bool              JvmtiExport::_can_post_interpreter_events               = false;
1191 bool              JvmtiExport::_can_post_on_exceptions                    = false;
1192 bool              JvmtiExport::_can_post_breakpoint                       = false;
1193 bool              JvmtiExport::_can_post_field_access                     = false;
1194 bool              JvmtiExport::_can_post_field_modification               = false;
1195 bool              JvmtiExport::_can_post_method_entry                     = false;
1196 bool              JvmtiExport::_can_post_method_exit                      = false;

1197 bool              JvmtiExport::_can_pop_frame                             = false;
1198 bool              JvmtiExport::_can_force_early_return                    = false;

1199 bool              JvmtiExport::_can_get_owned_monitor_info                = false;
1200 
1201 bool              JvmtiExport::_early_vmstart_recorded                    = false;
1202 
1203 bool              JvmtiExport::_should_post_single_step                   = false;
1204 bool              JvmtiExport::_should_post_field_access                  = false;
1205 bool              JvmtiExport::_should_post_field_modification            = false;
1206 bool              JvmtiExport::_should_post_class_load                    = false;
1207 bool              JvmtiExport::_should_post_class_prepare                 = false;
1208 bool              JvmtiExport::_should_post_class_unload                  = false;
1209 bool              JvmtiExport::_should_post_thread_life                   = false;
1210 bool              JvmtiExport::_should_clean_up_heap_objects              = false;
1211 bool              JvmtiExport::_should_post_native_method_bind            = false;
1212 bool              JvmtiExport::_should_post_dynamic_code_generated        = false;
1213 bool              JvmtiExport::_should_post_data_dump                     = false;
1214 bool              JvmtiExport::_should_post_compiled_method_load          = false;
1215 bool              JvmtiExport::_should_post_compiled_method_unload        = false;
1216 bool              JvmtiExport::_should_post_monitor_contended_enter       = false;
1217 bool              JvmtiExport::_should_post_monitor_contended_entered     = false;
1218 bool              JvmtiExport::_should_post_monitor_wait                  = false;
1219 bool              JvmtiExport::_should_post_monitor_waited                = false;
1220 bool              JvmtiExport::_should_post_garbage_collection_start      = false;
1221 bool              JvmtiExport::_should_post_garbage_collection_finish     = false;
1222 bool              JvmtiExport::_should_post_object_free                   = false;
1223 bool              JvmtiExport::_should_post_resource_exhausted            = false;
1224 bool              JvmtiExport::_should_post_vm_object_alloc               = false;
1225 bool              JvmtiExport::_should_post_sampled_object_alloc          = false;
1226 bool              JvmtiExport::_should_post_on_exceptions                 = false;




1227 
1228 ////////////////////////////////////////////////////////////////////////////////////////////////
1229 
1230 





























1231 //
1232 // JVMTI single step management
1233 //
1234 void JvmtiExport::at_single_stepping_point(JavaThread *thread, Method* method, address location) {
1235   assert(JvmtiExport::should_post_single_step(), "must be single stepping");
1236 
1237   HandleMark hm(thread);
1238   methodHandle mh(thread, method);
1239 
1240   // update information about current location and post a step event
1241   JvmtiThreadState *state = thread->jvmti_thread_state();
1242   if (state == NULL) {
1243     return;
1244   }
1245   EVT_TRIG_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Trg Single Step triggered",
1246                       JvmtiTrace::safe_get_thread_name(thread)));
1247   if (!state->hide_single_stepping()) {
1248     if (state->is_pending_step_for_popframe()) {
1249       state->process_pending_step_for_popframe();
1250     }
1251     if (state->is_pending_step_for_earlyret()) {
1252       state->process_pending_step_for_earlyret();
1253     }
1254     JvmtiExport::post_single_step(thread, mh(), location);
1255   }
1256 }
1257 
1258 
1259 void JvmtiExport::expose_single_stepping(JavaThread *thread) {
1260   JvmtiThreadState *state = thread->jvmti_thread_state();
1261   if (state != NULL) {
1262     state->clear_hide_single_stepping();
1263   }
1264 }
1265 
1266 
1267 bool JvmtiExport::hide_single_stepping(JavaThread *thread) {
1268   JvmtiThreadState *state = thread->jvmti_thread_state();
1269   if (state != NULL && state->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1270     state->set_hide_single_stepping();
1271     return true;
1272   } else {
1273     return false;
1274   }
1275 }
1276 
1277 void JvmtiExport::post_class_load(JavaThread *thread, Klass* klass) {
1278   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1279     return;
1280   }
1281   HandleMark hm(thread);
1282 
1283   EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Trg Class Load triggered",
1284                       JvmtiTrace::safe_get_thread_name(thread)));
1285   JvmtiThreadState* state = thread->jvmti_thread_state();
1286   if (state == NULL) {
1287     return;
1288   }



1289   JvmtiEnvThreadStateIterator it(state);
1290   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1291     if (ets->is_enabled(JVMTI_EVENT_CLASS_LOAD)) {
1292       JvmtiEnv *env = ets->get_env();
1293       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1294         continue;
1295       }
1296       EVT_TRACE(JVMTI_EVENT_CLASS_LOAD, ("[%s] Evt Class Load sent %s",
1297                                          JvmtiTrace::safe_get_thread_name(thread),
1298                                          klass==NULL? "NULL" : klass->external_name() ));
1299       JvmtiClassEventMark jem(thread, klass);
1300       JvmtiJavaThreadEventTransition jet(thread);
1301       jvmtiEventClassLoad callback = env->callbacks()->ClassLoad;
1302       if (callback != NULL) {
1303         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1304       }
1305     }
1306   }
1307 }
1308 
1309 
1310 void JvmtiExport::post_class_prepare(JavaThread *thread, Klass* klass) {
1311   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1312     return;
1313   }
1314   HandleMark hm(thread);
1315 
1316   EVT_TRIG_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Trg Class Prepare triggered",
1317                       JvmtiTrace::safe_get_thread_name(thread)));
1318   JvmtiThreadState* state = thread->jvmti_thread_state();
1319   if (state == NULL) {
1320     return;
1321   }



1322   JvmtiEnvThreadStateIterator it(state);
1323   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1324     if (ets->is_enabled(JVMTI_EVENT_CLASS_PREPARE)) {
1325       JvmtiEnv *env = ets->get_env();
1326       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1327         continue;
1328       }
1329       EVT_TRACE(JVMTI_EVENT_CLASS_PREPARE, ("[%s] Evt Class Prepare sent %s",
1330                                             JvmtiTrace::safe_get_thread_name(thread),
1331                                             klass==NULL? "NULL" : klass->external_name() ));
1332       JvmtiClassEventMark jem(thread, klass);
1333       JvmtiJavaThreadEventTransition jet(thread);
1334       jvmtiEventClassPrepare callback = env->callbacks()->ClassPrepare;
1335       if (callback != NULL) {
1336         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_class());
1337       }
1338     }
1339   }
1340 }
1341 
1342 void JvmtiExport::post_class_unload(Klass* klass) {
1343   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1344     return;
1345   }
1346 
1347   // postings to the service thread so that it can perform them in a safe
1348   // context and in-order.
1349   ResourceMark rm;
1350   // JvmtiDeferredEvent copies the string.
1351   JvmtiDeferredEvent event = JvmtiDeferredEvent::class_unload_event(klass->name()->as_C_string());
1352   ServiceThread::enqueue_deferred_event(&event);
1353 }
1354 
1355 
1356 void JvmtiExport::post_class_unload_internal(const char* name) {
1357   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1358     return;
1359   }
1360   assert(Thread::current()->is_service_thread(), "must be called from ServiceThread");
1361   JavaThread *thread = JavaThread::current();
1362   HandleMark hm(thread);
1363 
1364   EVT_TRIG_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Trg Class Unload triggered" ));
1365   if (JvmtiEventController::is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1366 
1367     JvmtiEnvIterator it;
1368     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1369       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1370         continue;
1371       }
1372       if (env->is_enabled((jvmtiEvent)EXT_EVENT_CLASS_UNLOAD)) {
1373         EVT_TRACE(EXT_EVENT_CLASS_UNLOAD, ("[?] Evt Class Unload sent %s", name));
1374 
1375         JvmtiEventMark jem(thread);
1376         JvmtiJavaThreadEventTransition jet(thread);
1377         jvmtiExtensionEvent callback = env->ext_callbacks()->ClassUnload;
1378         if (callback != NULL) {
1379           (*callback)(env->jvmti_external(), jem.jni_env(), name);
1380         }
1381       }
1382     }
1383   }
1384 }
1385 
1386 
1387 void JvmtiExport::post_thread_start(JavaThread *thread) {
1388   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1389     return;
1390   }
1391   assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
1392 
1393   EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Trg Thread Start event triggered",
1394                       JvmtiTrace::safe_get_thread_name(thread)));
1395 
1396   // do JVMTI thread initialization (if needed)
1397   JvmtiEventController::thread_started(thread);
1398 
1399   // Do not post thread start event for hidden java thread.
1400   if (JvmtiEventController::is_enabled(JVMTI_EVENT_THREAD_START) &&
1401       !thread->is_hidden_from_external_view()) {
1402     JvmtiEnvIterator it;
1403     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1404       if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1405         continue;
1406       }
1407       if (env->is_enabled(JVMTI_EVENT_THREAD_START)) {
1408         EVT_TRACE(JVMTI_EVENT_THREAD_START, ("[%s] Evt Thread Start event sent",
1409                      JvmtiTrace::safe_get_thread_name(thread) ));
1410 
1411         JvmtiThreadEventMark jem(thread);
1412         JvmtiJavaThreadEventTransition jet(thread);
1413         jvmtiEventThreadStart callback = env->callbacks()->ThreadStart;
1414         if (callback != NULL) {
1415           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1416         }
1417       }
1418     }
1419   }
1420 }
1421 
1422 
1423 void JvmtiExport::post_thread_end(JavaThread *thread) {
1424   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
1425     return;
1426   }
1427   EVT_TRIG_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Trg Thread End event triggered",
1428                       JvmtiTrace::safe_get_thread_name(thread)));
1429 
1430   JvmtiThreadState *state = thread->jvmti_thread_state();
1431   if (state == NULL) {
1432     return;
1433   }
1434 
1435   // Do not post thread end event for hidden java thread.
1436   if (state->is_enabled(JVMTI_EVENT_THREAD_END) &&
1437       !thread->is_hidden_from_external_view()) {
1438 
1439     JvmtiEnvThreadStateIterator it(state);
1440     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1441       if (ets->is_enabled(JVMTI_EVENT_THREAD_END)) {
1442         JvmtiEnv *env = ets->get_env();
1443         if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
1444           continue;
1445         }
1446         EVT_TRACE(JVMTI_EVENT_THREAD_END, ("[%s] Evt Thread End event sent",
1447                      JvmtiTrace::safe_get_thread_name(thread) ));
1448 
1449         JvmtiThreadEventMark jem(thread);
1450         JvmtiJavaThreadEventTransition jet(thread);
1451         jvmtiEventThreadEnd callback = env->callbacks()->ThreadEnd;
1452         if (callback != NULL) {
1453           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread());
1454         }
1455       }
1456     }
1457   }
1458 }
1459 













































































































































































1460 void JvmtiExport::post_object_free(JvmtiEnv* env, jlong tag) {
1461   assert(env->is_enabled(JVMTI_EVENT_OBJECT_FREE), "checking");
1462 
1463   EVT_TRIG_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Trg Object Free triggered" ));
1464   EVT_TRACE(JVMTI_EVENT_OBJECT_FREE, ("[?] Evt Object Free sent"));
1465 
1466   jvmtiEventObjectFree callback = env->callbacks()->ObjectFree;
1467   if (callback != NULL) {
1468     (*callback)(env->jvmti_external(), tag);
1469   }
1470 }
1471 
1472 void JvmtiExport::post_resource_exhausted(jint resource_exhausted_flags, const char* description) {
1473 
1474   JavaThread *thread  = JavaThread::current();
1475 
1476   log_error(jvmti)("Posting Resource Exhausted event: %s",
1477                    description != nullptr ? description : "unknown");
1478 
1479   // JDK-8213834: handlers of ResourceExhausted may attempt some analysis
1480   // which often requires running java.
1481   // This will cause problems on threads not able to run java, e.g. compiler
1482   // threads. To forestall these problems, we therefore suppress sending this
1483   // event from threads which are not able to run java.
1484   if (!thread->can_call_java()) {
1485     return;
1486   }
1487 
1488   EVT_TRIG_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Trg resource exhausted event triggered" ));
1489 
1490   JvmtiEnvIterator it;
1491   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
1492     if (env->is_enabled(JVMTI_EVENT_RESOURCE_EXHAUSTED)) {
1493       EVT_TRACE(JVMTI_EVENT_RESOURCE_EXHAUSTED, ("Evt resource exhausted event sent" ));
1494 
1495       JvmtiThreadEventMark jem(thread);
1496       JvmtiJavaThreadEventTransition jet(thread);
1497       jvmtiEventResourceExhausted callback = env->callbacks()->ResourceExhausted;
1498       if (callback != NULL) {
1499         (*callback)(env->jvmti_external(), jem.jni_env(),
1500                     resource_exhausted_flags, NULL, description);
1501       }
1502     }
1503   }
1504 }
1505 
1506 void JvmtiExport::post_method_entry(JavaThread *thread, Method* method, frame current_frame) {
1507   HandleMark hm(thread);
1508   methodHandle mh(thread, method);
1509 
1510   EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Trg Method Entry triggered %s.%s",
1511                      JvmtiTrace::safe_get_thread_name(thread),
1512                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1513                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1514 
1515   JvmtiThreadState* state = thread->jvmti_thread_state();
1516   if (state == NULL || !state->is_interp_only_mode()) {
1517     // for any thread that actually wants method entry, interp_only_mode is set
1518     return;
1519   }



1520 
1521   state->incr_cur_stack_depth();
1522 
1523   if (state->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1524     JvmtiEnvThreadStateIterator it(state);
1525     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1526       if (ets->is_enabled(JVMTI_EVENT_METHOD_ENTRY)) {
1527         EVT_TRACE(JVMTI_EVENT_METHOD_ENTRY, ("[%s] Evt Method Entry sent %s.%s",
1528                                              JvmtiTrace::safe_get_thread_name(thread),
1529                                              (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1530                                              (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1531 
1532         JvmtiEnv *env = ets->get_env();
1533         JvmtiMethodEventMark jem(thread, mh);
1534         JvmtiJavaThreadEventTransition jet(thread);
1535         jvmtiEventMethodEntry callback = env->callbacks()->MethodEntry;
1536         if (callback != NULL) {
1537           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_methodID());
1538         }
1539       }
1540     }
1541   }
1542 }
1543 
1544 void JvmtiExport::post_method_exit(JavaThread* thread, Method* method, frame current_frame) {
1545   HandleMark hm(thread);
1546   methodHandle mh(thread, method);
1547 
1548   JvmtiThreadState *state = thread->jvmti_thread_state();
1549 
1550   if (state == NULL || !state->is_interp_only_mode()) {
1551     // for any thread that actually wants method exit, interp_only_mode is set
1552     return;
1553   }



1554 
1555   // return a flag when a method terminates by throwing an exception
1556   // i.e. if an exception is thrown and it's not caught by the current method
1557   bool exception_exit = state->is_exception_detected() && !state->is_exception_caught();
1558   Handle result;
1559   jvalue value;
1560   value.j = 0L;
1561 
1562   if (state->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1563     // if the method hasn't been popped because of an exception then we populate
1564     // the return_value parameter for the callback. At this point we only have
1565     // the address of a "raw result" and we just call into the interpreter to
1566     // convert this into a jvalue.
1567     if (!exception_exit) {
1568       oop oop_result;
1569       BasicType type = current_frame.interpreter_frame_result(&oop_result, &value);
1570       if (is_reference_type(type)) {
1571         result = Handle(thread, oop_result);
1572         value.l = JNIHandles::make_local(thread, result());
1573       }
1574     }
1575   }
1576 
1577   // Deferred transition to VM, so we can stash away the return oop before GC
1578   // Note that this transition is not needed when throwing an exception, because
1579   // there is no oop to retain.
1580   JavaThread* current = thread; // for JRT_BLOCK
1581   JRT_BLOCK
1582     post_method_exit_inner(thread, mh, state, exception_exit, current_frame, value);
1583   JRT_BLOCK_END
1584 
1585   if (result.not_null() && !mh->is_native()) {
1586     // We have to restore the oop on the stack for interpreter frames
1587     *(oop*)current_frame.interpreter_frame_tos_address() = result();
1588   }
1589 }
1590 
1591 void JvmtiExport::post_method_exit_inner(JavaThread* thread,
1592                                          methodHandle& mh,
1593                                          JvmtiThreadState *state,
1594                                          bool exception_exit,
1595                                          frame current_frame,
1596                                          jvalue& value) {
1597   EVT_TRIG_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Trg Method Exit triggered %s.%s",
1598                                            JvmtiTrace::safe_get_thread_name(thread),
1599                                            (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1600                                            (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1601 
1602   if (state->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1603     JvmtiEnvThreadStateIterator it(state);
1604     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1605       if (ets->is_enabled(JVMTI_EVENT_METHOD_EXIT)) {
1606         EVT_TRACE(JVMTI_EVENT_METHOD_EXIT, ("[%s] Evt Method Exit sent %s.%s",
1607                                             JvmtiTrace::safe_get_thread_name(thread),
1608                                             (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1609                                             (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1610 
1611         JvmtiEnv *env = ets->get_env();
1612         JvmtiMethodEventMark jem(thread, mh);
1613         JvmtiJavaThreadEventTransition jet(thread);
1614         jvmtiEventMethodExit callback = env->callbacks()->MethodExit;
1615         if (callback != NULL) {
1616           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1617                       jem.jni_methodID(), exception_exit,  value);
1618         }
1619       }
1620     }
1621   }
1622 
1623   JvmtiEnvThreadStateIterator it(state);
1624   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1625     if (ets->has_frame_pops()) {
1626       int cur_frame_number = state->cur_stack_depth();
1627 
1628       if (ets->is_frame_pop(cur_frame_number)) {
1629         // we have a NotifyFramePop entry for this frame.
1630         // now check that this env/thread wants this event
1631         if (ets->is_enabled(JVMTI_EVENT_FRAME_POP)) {
1632           EVT_TRACE(JVMTI_EVENT_FRAME_POP, ("[%s] Evt Frame Pop sent %s.%s",
1633                                             JvmtiTrace::safe_get_thread_name(thread),
1634                                             (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1635                                             (mh() == NULL) ? "NULL" : mh()->name()->as_C_string() ));
1636 
1637           // we also need to issue a frame pop event for this frame
1638           JvmtiEnv *env = ets->get_env();
1639           JvmtiMethodEventMark jem(thread, mh);
1640           JvmtiJavaThreadEventTransition jet(thread);
1641           jvmtiEventFramePop callback = env->callbacks()->FramePop;
1642           if (callback != NULL) {
1643             (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1644                         jem.jni_methodID(), exception_exit);
1645           }
1646         }
1647         // remove the frame's entry
1648         {
1649           MutexLocker mu(JvmtiThreadState_lock);
1650           ets->clear_frame_pop(cur_frame_number);
1651         }
1652       }
1653     }
1654   }
1655 
1656   state->decr_cur_stack_depth();

1657 }
1658 
1659 
1660 // Todo: inline this for optimization
1661 void JvmtiExport::post_single_step(JavaThread *thread, Method* method, address location) {
1662   HandleMark hm(thread);
1663   methodHandle mh(thread, method);
1664 
1665   JvmtiThreadState *state = thread->jvmti_thread_state();
1666   if (state == NULL) {
1667     return;
1668   }




1669   JvmtiEnvThreadStateIterator it(state);
1670   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1671     ets->compare_and_set_current_location(mh(), location, JVMTI_EVENT_SINGLE_STEP);
1672     if (!ets->single_stepping_posted() && ets->is_enabled(JVMTI_EVENT_SINGLE_STEP)) {
1673       EVT_TRACE(JVMTI_EVENT_SINGLE_STEP, ("[%s] Evt Single Step sent %s.%s @ " INTX_FORMAT,
1674                     JvmtiTrace::safe_get_thread_name(thread),
1675                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1676                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1677                     location - mh()->code_base() ));
1678 
1679       JvmtiEnv *env = ets->get_env();
1680       JvmtiLocationEventMark jem(thread, mh, location);
1681       JvmtiJavaThreadEventTransition jet(thread);
1682       jvmtiEventSingleStep callback = env->callbacks()->SingleStep;
1683       if (callback != NULL) {
1684         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1685                     jem.jni_methodID(), jem.location());
1686       }
1687 
1688       ets->set_single_stepping_posted();
1689     }
1690   }
1691 }
1692 
1693 void JvmtiExport::post_exception_throw(JavaThread *thread, Method* method, address location, oop exception) {
1694   HandleMark hm(thread);
1695   methodHandle mh(thread, method);
1696   Handle exception_handle(thread, exception);
1697 
1698   JvmtiThreadState *state = thread->jvmti_thread_state();
1699   if (state == NULL) {
1700     return;
1701   }



1702 
1703   EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION, ("[%s] Trg Exception thrown triggered",
1704                       JvmtiTrace::safe_get_thread_name(thread)));
1705   if (!state->is_exception_detected()) {
1706     state->set_exception_detected();
1707     JvmtiEnvThreadStateIterator it(state);
1708     for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1709       if (ets->is_enabled(JVMTI_EVENT_EXCEPTION) && (exception != NULL)) {
1710 
1711         EVT_TRACE(JVMTI_EVENT_EXCEPTION,
1712                      ("[%s] Evt Exception thrown sent %s.%s @ " INTX_FORMAT,
1713                       JvmtiTrace::safe_get_thread_name(thread),
1714                       (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1715                       (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1716                       location - mh()->code_base() ));
1717 
1718         JvmtiEnv *env = ets->get_env();
1719         JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1720 
1721         // It's okay to clear these exceptions here because we duplicate
1722         // this lookup in InterpreterRuntime::exception_handler_for_exception.
1723         EXCEPTION_MARK;
1724 
1725         bool should_repeat;
1726         vframeStream st(thread);
1727         assert(!st.at_end(), "cannot be at end");
1728         Method* current_method = NULL;
1729         // A GC may occur during the Method::fast_exception_handler_bci_for()
1730         // call below if it needs to load the constraint class. Using a
1731         // methodHandle to keep the 'current_method' from being deallocated
1732         // if GC happens.
1733         methodHandle current_mh = methodHandle(thread, current_method);
1734         int current_bci = -1;
1735         do {
1736           current_method = st.method();
1737           current_mh = methodHandle(thread, current_method);
1738           current_bci = st.bci();
1739           do {
1740             should_repeat = false;
1741             Klass* eh_klass = exception_handle()->klass();
1742             current_bci = Method::fast_exception_handler_bci_for(
1743               current_mh, eh_klass, current_bci, THREAD);
1744             if (HAS_PENDING_EXCEPTION) {
1745               exception_handle = Handle(thread, PENDING_EXCEPTION);
1746               CLEAR_PENDING_EXCEPTION;
1747               should_repeat = true;
1748             }
1749           } while (should_repeat && (current_bci != -1));
1750           st.next();
1751         } while ((current_bci < 0) && (!st.at_end()));
1752 
1753         jmethodID catch_jmethodID;
1754         if (current_bci < 0) {
1755           catch_jmethodID = 0;
1756           current_bci = 0;
1757         } else {
1758           catch_jmethodID = jem.to_jmethodID(current_mh);
1759         }
1760 
1761         JvmtiJavaThreadEventTransition jet(thread);
1762         jvmtiEventException callback = env->callbacks()->Exception;
1763         if (callback != NULL) {
1764           (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1765                       jem.jni_methodID(), jem.location(),
1766                       jem.exception(),
1767                       catch_jmethodID, current_bci);
1768         }
1769       }
1770     }
1771   }
1772 
1773   // frames may get popped because of this throw, be safe - invalidate cached depth
1774   state->invalidate_cur_stack_depth();
1775 }
1776 
1777 
1778 void JvmtiExport::notice_unwind_due_to_exception(JavaThread *thread, Method* method, address location, oop exception, bool in_handler_frame) {
1779   HandleMark hm(thread);
1780   methodHandle mh(thread, method);
1781   Handle exception_handle(thread, exception);
1782 
1783   JvmtiThreadState *state = thread->jvmti_thread_state();
1784   if (state == NULL) {
1785     return;
1786   }
1787   EVT_TRIG_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1788                     ("[%s] Trg unwind_due_to_exception triggered %s.%s @ %s" INTX_FORMAT " - %s",
1789                      JvmtiTrace::safe_get_thread_name(thread),
1790                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1791                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1792                      location==0? "no location:" : "",
1793                      location==0? 0 : location - mh()->code_base(),
1794                      in_handler_frame? "in handler frame" : "not handler frame" ));
1795 
1796   if (state->is_exception_detected()) {
1797 
1798     state->invalidate_cur_stack_depth();
1799     if (!in_handler_frame) {
1800       // Not in exception handler.
1801       if(state->is_interp_only_mode()) {
1802         // method exit and frame pop events are posted only in interp mode.
1803         // When these events are enabled code should be in running in interp mode.
1804         jvalue no_value;
1805         no_value.j = 0L;
1806         JvmtiExport::post_method_exit_inner(thread, mh, state, true, thread->last_frame(), no_value);
1807         // The cached cur_stack_depth might have changed from the
1808         // operations of frame pop or method exit. We are not 100% sure
1809         // the cached cur_stack_depth is still valid depth so invalidate
1810         // it.
1811         state->invalidate_cur_stack_depth();
1812       }
1813     } else {
1814       // In exception handler frame. Report exception catch.
1815       assert(location != NULL, "must be a known location");
1816       // Update cur_stack_depth - the frames above the current frame
1817       // have been unwound due to this exception:
1818       assert(!state->is_exception_caught(), "exception must not be caught yet.");
1819       state->set_exception_caught();
1820 
1821       JvmtiEnvThreadStateIterator it(state);
1822       for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1823         if (ets->is_enabled(JVMTI_EVENT_EXCEPTION_CATCH) && (exception_handle() != NULL)) {
1824           EVT_TRACE(JVMTI_EVENT_EXCEPTION_CATCH,
1825                      ("[%s] Evt ExceptionCatch sent %s.%s @ " INTX_FORMAT,
1826                       JvmtiTrace::safe_get_thread_name(thread),
1827                       (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1828                       (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1829                       location - mh()->code_base() ));
1830 
1831           JvmtiEnv *env = ets->get_env();
1832           JvmtiExceptionEventMark jem(thread, mh, location, exception_handle);
1833           JvmtiJavaThreadEventTransition jet(thread);
1834           jvmtiEventExceptionCatch callback = env->callbacks()->ExceptionCatch;
1835           if (callback != NULL) {
1836             (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1837                       jem.jni_methodID(), jem.location(),
1838                       jem.exception());
1839           }
1840         }
1841       }
1842     }
1843   }
1844 }
1845 
1846 oop JvmtiExport::jni_GetField_probe(JavaThread *thread, jobject jobj, oop obj,
1847                                     Klass* klass, jfieldID fieldID, bool is_static) {
1848   if (*((int *)get_field_access_count_addr()) > 0 && thread->has_last_Java_frame()) {
1849     // At least one field access watch is set so we have more work to do.
1850     post_field_access_by_jni(thread, obj, klass, fieldID, is_static);
1851     // event posting can block so refetch oop if we were passed a jobj
1852     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1853   }
1854   return obj;
1855 }
1856 
1857 void JvmtiExport::post_field_access_by_jni(JavaThread *thread, oop obj,
1858                                            Klass* klass, jfieldID fieldID, bool is_static) {
1859   // We must be called with a Java context in order to provide reasonable
1860   // values for the klazz, method, and location fields. The callers of this
1861   // function don't make the call unless there is a Java context.
1862   assert(thread->has_last_Java_frame(), "must be called with a Java context");
1863 




1864   ResourceMark rm;
1865   fieldDescriptor fd;
1866   // if get_field_descriptor finds fieldID to be invalid, then we just bail
1867   bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1868   assert(valid_fieldID == true,"post_field_access_by_jni called with invalid fieldID");
1869   if (!valid_fieldID) return;
1870   // field accesses are not watched so bail
1871   if (!fd.is_field_access_watched()) return;
1872 
1873   HandleMark hm(thread);
1874   Handle h_obj;
1875   if (!is_static) {
1876     // non-static field accessors have an object, but we need a handle
1877     assert(obj != NULL, "non-static needs an object");
1878     h_obj = Handle(thread, obj);
1879   }
1880   post_field_access(thread,
1881                     thread->last_frame().interpreter_frame_method(),
1882                     thread->last_frame().interpreter_frame_bcp(),
1883                     klass, h_obj, fieldID);
1884 }
1885 
1886 void JvmtiExport::post_field_access(JavaThread *thread, Method* method,
1887   address location, Klass* field_klass, Handle object, jfieldID field) {
1888 
1889   HandleMark hm(thread);
1890   methodHandle mh(thread, method);
1891 
1892   JvmtiThreadState *state = thread->jvmti_thread_state();
1893   if (state == NULL) {
1894     return;
1895   }




1896   EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Trg Field Access event triggered",
1897                       JvmtiTrace::safe_get_thread_name(thread)));
1898   JvmtiEnvThreadStateIterator it(state);
1899   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
1900     if (ets->is_enabled(JVMTI_EVENT_FIELD_ACCESS)) {
1901       EVT_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Evt Field Access event sent %s.%s @ " INTX_FORMAT,
1902                      JvmtiTrace::safe_get_thread_name(thread),
1903                      (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
1904                      (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
1905                      location - mh()->code_base() ));
1906 
1907       JvmtiEnv *env = ets->get_env();
1908       JvmtiLocationEventMark jem(thread, mh, location);
1909       jclass field_jclass = jem.to_jclass(field_klass);
1910       jobject field_jobject = jem.to_jobject(object());
1911       JvmtiJavaThreadEventTransition jet(thread);
1912       jvmtiEventFieldAccess callback = env->callbacks()->FieldAccess;
1913       if (callback != NULL) {
1914         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
1915                     jem.jni_methodID(), jem.location(),
1916                     field_jclass, field_jobject, field);
1917       }
1918     }
1919   }
1920 }
1921 
1922 oop JvmtiExport::jni_SetField_probe(JavaThread *thread, jobject jobj, oop obj,
1923                                     Klass* klass, jfieldID fieldID, bool is_static,
1924                                     char sig_type, jvalue *value) {
1925   if (*((int *)get_field_modification_count_addr()) > 0 && thread->has_last_Java_frame()) {
1926     // At least one field modification watch is set so we have more work to do.
1927     post_field_modification_by_jni(thread, obj, klass, fieldID, is_static, sig_type, value);
1928     // event posting can block so refetch oop if we were passed a jobj
1929     if (jobj != NULL) return JNIHandles::resolve_non_null(jobj);
1930   }
1931   return obj;
1932 }
1933 
1934 void JvmtiExport::post_field_modification_by_jni(JavaThread *thread, oop obj,
1935                                                  Klass* klass, jfieldID fieldID, bool is_static,
1936                                                  char sig_type, jvalue *value) {
1937   // We must be called with a Java context in order to provide reasonable
1938   // values for the klazz, method, and location fields. The callers of this
1939   // function don't make the call unless there is a Java context.
1940   assert(thread->has_last_Java_frame(), "must be called with Java context");
1941 




1942   ResourceMark rm;
1943   fieldDescriptor fd;
1944   // if get_field_descriptor finds fieldID to be invalid, then we just bail
1945   bool valid_fieldID = JvmtiEnv::get_field_descriptor(klass, fieldID, &fd);
1946   assert(valid_fieldID == true,"post_field_modification_by_jni called with invalid fieldID");
1947   if (!valid_fieldID) return;
1948   // field modifications are not watched so bail
1949   if (!fd.is_field_modification_watched()) return;
1950 
1951   HandleMark hm(thread);
1952 
1953   Handle h_obj;
1954   if (!is_static) {
1955     // non-static field accessors have an object, but we need a handle
1956     assert(obj != NULL, "non-static needs an object");
1957     h_obj = Handle(thread, obj);
1958   }
1959   post_field_modification(thread,
1960                           thread->last_frame().interpreter_frame_method(),
1961                           thread->last_frame().interpreter_frame_bcp(),
1962                           klass, h_obj, fieldID, sig_type, value);
1963 }
1964 
1965 void JvmtiExport::post_raw_field_modification(JavaThread *thread, Method* method,
1966   address location, Klass* field_klass, Handle object, jfieldID field,
1967   char sig_type, jvalue *value) {
1968 




1969   if (sig_type == JVM_SIGNATURE_INT || sig_type == JVM_SIGNATURE_BOOLEAN ||
1970       sig_type == JVM_SIGNATURE_BYTE || sig_type == JVM_SIGNATURE_CHAR ||
1971       sig_type == JVM_SIGNATURE_SHORT) {
1972     // 'I' instructions are used for byte, char, short and int.
1973     // determine which it really is, and convert
1974     fieldDescriptor fd;
1975     bool found = JvmtiEnv::get_field_descriptor(field_klass, field, &fd);
1976     // should be found (if not, leave as is)
1977     if (found) {
1978       jint ival = value->i;
1979       // convert value from int to appropriate type
1980       switch (fd.field_type()) {
1981       case T_BOOLEAN:
1982         sig_type = JVM_SIGNATURE_BOOLEAN;
1983         value->i = 0; // clear it
1984         value->z = (jboolean)ival;
1985         break;
1986       case T_BYTE:
1987         sig_type = JVM_SIGNATURE_BYTE;
1988         value->i = 0; // clear it
1989         value->b = (jbyte)ival;
1990         break;
1991       case T_CHAR:
1992         sig_type = JVM_SIGNATURE_CHAR;
1993         value->i = 0; // clear it
1994         value->c = (jchar)ival;
1995         break;
1996       case T_SHORT:
1997         sig_type = JVM_SIGNATURE_SHORT;
1998         value->i = 0; // clear it
1999         value->s = (jshort)ival;
2000         break;
2001       case T_INT:
2002         // nothing to do
2003         break;
2004       default:
2005         // this is an integer instruction, should be one of above
2006         ShouldNotReachHere();
2007         break;
2008       }
2009     }
2010   }
2011 
2012   assert(sig_type != JVM_SIGNATURE_ARRAY, "array should have sig_type == 'L'");
2013   bool handle_created = false;
2014 
2015   // convert oop to JNI handle.
2016   if (sig_type == JVM_SIGNATURE_CLASS) {
2017     handle_created = true;
2018     value->l = (jobject)JNIHandles::make_local(thread, cast_to_oop(value->l));
2019   }
2020 
2021   post_field_modification(thread, method, location, field_klass, object, field, sig_type, value);
2022 
2023   // Destroy the JNI handle allocated above.
2024   if (handle_created) {
2025     JNIHandles::destroy_local(value->l);
2026   }
2027 }
2028 
2029 void JvmtiExport::post_field_modification(JavaThread *thread, Method* method,
2030   address location, Klass* field_klass, Handle object, jfieldID field,
2031   char sig_type, jvalue *value_ptr) {
2032 
2033   HandleMark hm(thread);
2034   methodHandle mh(thread, method);
2035 
2036   JvmtiThreadState *state = thread->jvmti_thread_state();
2037   if (state == NULL) {
2038     return;
2039   }




2040   EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
2041                      ("[%s] Trg Field Modification event triggered",
2042                       JvmtiTrace::safe_get_thread_name(thread)));
2043 
2044   JvmtiEnvThreadStateIterator it(state);
2045   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2046     if (ets->is_enabled(JVMTI_EVENT_FIELD_MODIFICATION)) {
2047       EVT_TRACE(JVMTI_EVENT_FIELD_MODIFICATION,
2048                    ("[%s] Evt Field Modification event sent %s.%s @ " INTX_FORMAT,
2049                     JvmtiTrace::safe_get_thread_name(thread),
2050                     (mh() == NULL) ? "NULL" : mh()->klass_name()->as_C_string(),
2051                     (mh() == NULL) ? "NULL" : mh()->name()->as_C_string(),
2052                     location - mh()->code_base() ));
2053 
2054       JvmtiEnv *env = ets->get_env();
2055       JvmtiLocationEventMark jem(thread, mh, location);
2056       jclass field_jclass = jem.to_jclass(field_klass);
2057       jobject field_jobject = jem.to_jobject(object());
2058       JvmtiJavaThreadEventTransition jet(thread);
2059       jvmtiEventFieldModification callback = env->callbacks()->FieldModification;
2060       if (callback != NULL) {
2061         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2062                     jem.jni_methodID(), jem.location(),
2063                     field_jclass, field_jobject, field, sig_type, *value_ptr);
2064       }
2065     }
2066   }
2067 }
2068 
2069 void JvmtiExport::post_native_method_bind(Method* method, address* function_ptr) {
2070   JavaThread* thread = JavaThread::current();
2071   assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
2072 
2073   HandleMark hm(thread);
2074   methodHandle mh(thread, method);
2075 
2076   EVT_TRIG_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Trg Native Method Bind event triggered",
2077                       JvmtiTrace::safe_get_thread_name(thread)));
2078 




2079   if (JvmtiEventController::is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
2080     JvmtiEnvIterator it;
2081     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2082       if (env->is_enabled(JVMTI_EVENT_NATIVE_METHOD_BIND)) {
2083         EVT_TRACE(JVMTI_EVENT_NATIVE_METHOD_BIND, ("[%s] Evt Native Method Bind event sent",
2084                      JvmtiTrace::safe_get_thread_name(thread) ));
2085 
2086         JvmtiMethodEventMark jem(thread, mh);
2087         JvmtiJavaThreadEventTransition jet(thread);
2088         JNIEnv* jni_env = (env->phase() == JVMTI_PHASE_PRIMORDIAL) ? NULL : jem.jni_env();
2089         jvmtiEventNativeMethodBind callback = env->callbacks()->NativeMethodBind;
2090         if (callback != NULL) {
2091           (*callback)(env->jvmti_external(), jni_env, jem.jni_thread(),
2092                       jem.jni_methodID(), (void*)(*function_ptr), (void**)function_ptr);
2093         }
2094       }
2095     }
2096   }
2097 }
2098 
2099 // Returns a record containing inlining information for the given nmethod
2100 jvmtiCompiledMethodLoadInlineRecord* create_inline_record(nmethod* nm) {
2101   jint numstackframes = 0;
2102   jvmtiCompiledMethodLoadInlineRecord* record = (jvmtiCompiledMethodLoadInlineRecord*)NEW_RESOURCE_OBJ(jvmtiCompiledMethodLoadInlineRecord);
2103   record->header.kind = JVMTI_CMLR_INLINE_INFO;
2104   record->header.next = NULL;
2105   record->header.majorinfoversion = JVMTI_CMLR_MAJOR_VERSION_1;
2106   record->header.minorinfoversion = JVMTI_CMLR_MINOR_VERSION_0;
2107   record->numpcs = 0;
2108   for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
2109    if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
2110    record->numpcs++;
2111   }
2112   record->pcinfo = (PCStackInfo*)(NEW_RESOURCE_ARRAY(PCStackInfo, record->numpcs));
2113   int scope = 0;
2114   for(PcDesc* p = nm->scopes_pcs_begin(); p < nm->scopes_pcs_end(); p++) {
2115     if(p->scope_decode_offset() == DebugInformationRecorder::serialized_null) continue;
2116     void* pc_address = (void*)p->real_pc(nm);
2117     assert(pc_address != NULL, "pc_address must be non-null");
2118     record->pcinfo[scope].pc = pc_address;
2119     numstackframes=0;
2120     for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2121       numstackframes++;
2122     }
2123     assert(numstackframes != 0, "numstackframes must be nonzero.");
2124     record->pcinfo[scope].methods = (jmethodID *)NEW_RESOURCE_ARRAY(jmethodID, numstackframes);
2125     record->pcinfo[scope].bcis = (jint *)NEW_RESOURCE_ARRAY(jint, numstackframes);
2126     record->pcinfo[scope].numstackframes = numstackframes;
2127     int stackframe = 0;
2128     for(ScopeDesc* sd = nm->scope_desc_at(p->real_pc(nm));sd != NULL;sd = sd->sender()) {
2129       // 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()
2130       guarantee(sd->method() != NULL, "sd->method() cannot be null.");
2131       record->pcinfo[scope].methods[stackframe] = sd->method()->jmethod_id();
2132       record->pcinfo[scope].bcis[stackframe] = sd->bci();
2133       stackframe++;
2134     }
2135     scope++;
2136   }
2137   return record;
2138 }
2139 
2140 void JvmtiExport::post_compiled_method_load(nmethod *nm) {
2141   guarantee(!nm->is_unloading(), "nmethod isn't unloaded or unloading");
2142   if (JvmtiEnv::get_phase() < JVMTI_PHASE_PRIMORDIAL) {
2143     return;
2144   }
2145   JavaThread* thread = JavaThread::current();
2146 
2147   EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2148                  ("[%s] method compile load event triggered",
2149                  JvmtiTrace::safe_get_thread_name(thread)));
2150 
2151   JvmtiEnvIterator it;
2152   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2153     post_compiled_method_load(env, nm);
2154   }
2155 }
2156 
2157 // post a COMPILED_METHOD_LOAD event for a given environment
2158 void JvmtiExport::post_compiled_method_load(JvmtiEnv* env, nmethod *nm) {
2159   if (env->phase() == JVMTI_PHASE_PRIMORDIAL || !env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
2160     return;
2161   }
2162   jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
2163   if (callback == NULL) {
2164     return;
2165   }
2166   JavaThread* thread = JavaThread::current();
2167 
2168   EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
2169            ("[%s] method compile load event sent %s.%s  ",
2170             JvmtiTrace::safe_get_thread_name(thread),
2171             (nm->method() == NULL) ? "NULL" : nm->method()->klass_name()->as_C_string(),
2172             (nm->method() == NULL) ? "NULL" : nm->method()->name()->as_C_string()));
2173   ResourceMark rm(thread);
2174   HandleMark hm(thread);
2175 
2176   assert(!nm->is_zombie(), "nmethod zombie in post_compiled_method_load");
2177   // Add inlining information
2178   jvmtiCompiledMethodLoadInlineRecord* inlinerecord = create_inline_record(nm);
2179   // Pass inlining information through the void pointer
2180   JvmtiCompiledMethodLoadEventMark jem(thread, nm, inlinerecord);
2181   JvmtiJavaThreadEventTransition jet(thread);
2182   (*callback)(env->jvmti_external(), jem.jni_methodID(),
2183               jem.code_size(), jem.code_data(), jem.map_length(),
2184               jem.map(), jem.compile_info());
2185 }
2186 
2187 void JvmtiExport::post_dynamic_code_generated_internal(const char *name, const void *code_begin, const void *code_end) {
2188   assert(name != NULL && name[0] != '\0', "sanity check");
2189 
2190   JavaThread* thread = JavaThread::current();
2191   // In theory everyone coming thru here is in_vm but we need to be certain
2192   // because a callee will do a vm->native transition
2193   ThreadInVMfromUnknown __tiv;
2194 
2195   EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2196                  ("[%s] method dynamic code generated event triggered",
2197                  JvmtiTrace::safe_get_thread_name(thread)));
2198   JvmtiEnvIterator it;
2199   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2200     if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2201       EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2202                 ("[%s] dynamic code generated event sent for %s",
2203                 JvmtiTrace::safe_get_thread_name(thread), name));
2204       JvmtiEventMark jem(thread);
2205       JvmtiJavaThreadEventTransition jet(thread);
2206       jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2207       jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2208       if (callback != NULL) {
2209         (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2210       }
2211     }
2212   }
2213 }
2214 
2215 void JvmtiExport::post_dynamic_code_generated(const char *name, const void *code_begin, const void *code_end) {
2216   jvmtiPhase phase = JvmtiEnv::get_phase();
2217   if (phase == JVMTI_PHASE_PRIMORDIAL || phase == JVMTI_PHASE_START) {
2218     post_dynamic_code_generated_internal(name, code_begin, code_end);
2219   } else {
2220     // It may not be safe to post the event from this thread.  Defer all
2221     // postings to the service thread so that it can perform them in a safe
2222     // context and in-order.
2223     JvmtiDeferredEvent event = JvmtiDeferredEvent::dynamic_code_generated_event(
2224         name, code_begin, code_end);
2225     ServiceThread::enqueue_deferred_event(&event);
2226   }
2227 }
2228 
2229 
2230 // post a DYNAMIC_CODE_GENERATED event for a given environment
2231 // used by GenerateEvents
2232 void JvmtiExport::post_dynamic_code_generated(JvmtiEnv* env, const char *name,
2233                                               const void *code_begin, const void *code_end)
2234 {
2235   JavaThread* thread = JavaThread::current();
2236   EVT_TRIG_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2237                  ("[%s] dynamic code generated event triggered (by GenerateEvents)",
2238                   JvmtiTrace::safe_get_thread_name(thread)));
2239   if (env->is_enabled(JVMTI_EVENT_DYNAMIC_CODE_GENERATED)) {
2240     EVT_TRACE(JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
2241               ("[%s] dynamic code generated event sent for %s",
2242                JvmtiTrace::safe_get_thread_name(thread), name));
2243     JvmtiEventMark jem(thread);
2244     JvmtiJavaThreadEventTransition jet(thread);
2245     jint length = (jint)pointer_delta(code_end, code_begin, sizeof(char));
2246     jvmtiEventDynamicCodeGenerated callback = env->callbacks()->DynamicCodeGenerated;
2247     if (callback != NULL) {
2248       (*callback)(env->jvmti_external(), name, (void*)code_begin, length);
2249     }
2250   }
2251 }
2252 
2253 // post a DynamicCodeGenerated event while holding locks in the VM.
2254 void JvmtiExport::post_dynamic_code_generated_while_holding_locks(const char* name,
2255                                                                   address code_begin, address code_end)
2256 {
2257   // register the stub with the current dynamic code event collector
2258   // Cannot take safepoint here so do not use state_for to get
2259   // jvmti thread state.
2260   // The collector and/or state might be NULL if JvmtiDynamicCodeEventCollector
2261   // has been initialized while JVMTI_EVENT_DYNAMIC_CODE_GENERATED was disabled.
2262   JvmtiThreadState* state = JavaThread::current()->jvmti_thread_state();
2263   if (state != NULL) {
2264     JvmtiDynamicCodeEventCollector *collector = state->get_dynamic_code_event_collector();
2265     if (collector != NULL) {
2266       collector->register_stub(name, code_begin, code_end);
2267     }
2268   }
2269 }
2270 
2271 // Collect all the vm internally allocated objects which are visible to java world
2272 void JvmtiExport::record_vm_internal_object_allocation(oop obj) {
2273   Thread* thread = Thread::current_or_null();
2274   if (thread != NULL && thread->is_Java_thread())  {
2275     // Can not take safepoint here.
2276     NoSafepointVerifier no_sfpt;
2277     // Cannot take safepoint here so do not use state_for to get
2278     // jvmti thread state.
2279     JvmtiThreadState *state = JavaThread::cast(thread)->jvmti_thread_state();
2280     if (state != NULL) {
2281       // state is non NULL when VMObjectAllocEventCollector is enabled.
2282       JvmtiVMObjectAllocEventCollector *collector;
2283       collector = state->get_vm_object_alloc_event_collector();
2284       if (collector != NULL && collector->is_enabled()) {
2285         // Don't record classes as these will be notified via the ClassLoad
2286         // event.
2287         if (obj->klass() != vmClasses::Class_klass()) {
2288           collector->record_allocation(obj);
2289         }
2290       }
2291     }
2292   }
2293 }
2294 
2295 // Collect all the sampled allocated objects.
2296 void JvmtiExport::record_sampled_internal_object_allocation(oop obj) {
2297   Thread* thread = Thread::current_or_null();
2298   if (thread != NULL && thread->is_Java_thread())  {
2299     // Can not take safepoint here.
2300     NoSafepointVerifier no_sfpt;
2301     // Cannot take safepoint here so do not use state_for to get
2302     // jvmti thread state.
2303     JvmtiThreadState *state = JavaThread::cast(thread)->jvmti_thread_state();
2304     if (state != NULL) {
2305       // state is non NULL when SampledObjectAllocEventCollector is enabled.
2306       JvmtiSampledObjectAllocEventCollector *collector;
2307       collector = state->get_sampled_object_alloc_event_collector();
2308 
2309       if (collector != NULL && collector->is_enabled()) {
2310         collector->record_allocation(obj);
2311       }
2312     }
2313   }
2314 }
2315 
2316 void JvmtiExport::post_garbage_collection_finish() {
2317   Thread *thread = Thread::current(); // this event is posted from VM-Thread.
2318   EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2319                  ("[%s] garbage collection finish event triggered",
2320                   JvmtiTrace::safe_get_thread_name(thread)));
2321   JvmtiEnvIterator it;
2322   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2323     if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH)) {
2324       EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
2325                 ("[%s] garbage collection finish event sent",
2326                  JvmtiTrace::safe_get_thread_name(thread)));
2327       JvmtiThreadEventTransition jet(thread);
2328       // JNIEnv is NULL here because this event is posted from VM Thread
2329       jvmtiEventGarbageCollectionFinish callback = env->callbacks()->GarbageCollectionFinish;
2330       if (callback != NULL) {
2331         (*callback)(env->jvmti_external());
2332       }
2333     }
2334   }
2335 }
2336 
2337 void JvmtiExport::post_garbage_collection_start() {
2338   Thread* thread = Thread::current(); // this event is posted from vm-thread.
2339   EVT_TRIG_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2340                  ("[%s] garbage collection start event triggered",
2341                   JvmtiTrace::safe_get_thread_name(thread)));
2342   JvmtiEnvIterator it;
2343   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2344     if (env->is_enabled(JVMTI_EVENT_GARBAGE_COLLECTION_START)) {
2345       EVT_TRACE(JVMTI_EVENT_GARBAGE_COLLECTION_START,
2346                 ("[%s] garbage collection start event sent",
2347                  JvmtiTrace::safe_get_thread_name(thread)));
2348       JvmtiThreadEventTransition jet(thread);
2349       // JNIEnv is NULL here because this event is posted from VM Thread
2350       jvmtiEventGarbageCollectionStart callback = env->callbacks()->GarbageCollectionStart;
2351       if (callback != NULL) {
2352         (*callback)(env->jvmti_external());
2353       }
2354     }
2355   }
2356 }
2357 
2358 void JvmtiExport::post_data_dump() {
2359   Thread *thread = Thread::current();
2360   EVT_TRIG_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2361                  ("[%s] data dump request event triggered",
2362                   JvmtiTrace::safe_get_thread_name(thread)));
2363   JvmtiEnvIterator it;
2364   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2365     if (env->is_enabled(JVMTI_EVENT_DATA_DUMP_REQUEST)) {
2366       EVT_TRACE(JVMTI_EVENT_DATA_DUMP_REQUEST,
2367                 ("[%s] data dump request event sent",
2368                  JvmtiTrace::safe_get_thread_name(thread)));
2369      JvmtiThreadEventTransition jet(thread);
2370      // JNIEnv is NULL here because this event is posted from VM Thread
2371      jvmtiEventDataDumpRequest callback = env->callbacks()->DataDumpRequest;
2372      if (callback != NULL) {
2373        (*callback)(env->jvmti_external());
2374      }
2375     }
2376   }
2377 }
2378 
2379 void JvmtiExport::post_monitor_contended_enter(JavaThread *thread, ObjectMonitor *obj_mntr) {
2380   oop object = obj_mntr->object();
2381   JvmtiThreadState *state = thread->jvmti_thread_state();
2382   if (state == NULL) {
2383     return;
2384   }



2385 
2386   HandleMark hm(thread);
2387   Handle h(thread, object);
2388 
2389   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2390                      ("[%s] monitor contended enter event triggered",
2391                       JvmtiTrace::safe_get_thread_name(thread)));
2392 
2393   JvmtiEnvThreadStateIterator it(state);
2394   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2395     if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTER)) {
2396       EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
2397                    ("[%s] monitor contended enter event sent",
2398                     JvmtiTrace::safe_get_thread_name(thread)));
2399       JvmtiMonitorEventMark  jem(thread, h());
2400       JvmtiEnv *env = ets->get_env();
2401       JvmtiThreadEventTransition jet(thread);
2402       jvmtiEventMonitorContendedEnter callback = env->callbacks()->MonitorContendedEnter;
2403       if (callback != NULL) {
2404         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2405       }
2406     }
2407   }
2408 }
2409 
2410 void JvmtiExport::post_monitor_contended_entered(JavaThread *thread, ObjectMonitor *obj_mntr) {
2411   oop object = obj_mntr->object();
2412   JvmtiThreadState *state = thread->jvmti_thread_state();
2413   if (state == NULL) {
2414     return;
2415   }



2416 
2417   HandleMark hm(thread);
2418   Handle h(thread, object);
2419 
2420   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2421                      ("[%s] monitor contended entered event triggered",
2422                       JvmtiTrace::safe_get_thread_name(thread)));
2423 
2424   JvmtiEnvThreadStateIterator it(state);
2425   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2426     if (ets->is_enabled(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED)) {
2427       EVT_TRACE(JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
2428                    ("[%s] monitor contended enter event sent",
2429                     JvmtiTrace::safe_get_thread_name(thread)));
2430       JvmtiMonitorEventMark  jem(thread, h());
2431       JvmtiEnv *env = ets->get_env();
2432       JvmtiThreadEventTransition jet(thread);
2433       jvmtiEventMonitorContendedEntered callback = env->callbacks()->MonitorContendedEntered;
2434       if (callback != NULL) {
2435         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(), jem.jni_object());
2436       }
2437     }
2438   }
2439 }
2440 
2441 void JvmtiExport::post_monitor_wait(JavaThread *thread, oop object,
2442                                           jlong timeout) {
2443   JvmtiThreadState *state = thread->jvmti_thread_state();
2444   if (state == NULL) {
2445     return;
2446   }



2447 
2448   HandleMark hm(thread);
2449   Handle h(thread, object);
2450 
2451   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2452                      ("[%s] monitor wait event triggered",
2453                       JvmtiTrace::safe_get_thread_name(thread)));
2454 
2455   JvmtiEnvThreadStateIterator it(state);
2456   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2457     if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAIT)) {
2458       EVT_TRACE(JVMTI_EVENT_MONITOR_WAIT,
2459                    ("[%s] monitor wait event sent",
2460                     JvmtiTrace::safe_get_thread_name(thread)));
2461       JvmtiMonitorEventMark  jem(thread, h());
2462       JvmtiEnv *env = ets->get_env();
2463       JvmtiThreadEventTransition jet(thread);
2464       jvmtiEventMonitorWait callback = env->callbacks()->MonitorWait;
2465       if (callback != NULL) {
2466         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2467                     jem.jni_object(), timeout);
2468       }
2469     }
2470   }
2471 }
2472 
2473 void JvmtiExport::post_monitor_waited(JavaThread *thread, ObjectMonitor *obj_mntr, jboolean timed_out) {
2474   oop object = obj_mntr->object();
2475   JvmtiThreadState *state = thread->jvmti_thread_state();
2476   if (state == NULL) {
2477     return;
2478   }



2479 
2480   HandleMark hm(thread);
2481   Handle h(thread, object);
2482 
2483   EVT_TRIG_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2484                      ("[%s] monitor waited event triggered",
2485                       JvmtiTrace::safe_get_thread_name(thread)));
2486 
2487   JvmtiEnvThreadStateIterator it(state);
2488   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2489     if (ets->is_enabled(JVMTI_EVENT_MONITOR_WAITED)) {
2490       EVT_TRACE(JVMTI_EVENT_MONITOR_WAITED,
2491                    ("[%s] monitor waited event sent",
2492                     JvmtiTrace::safe_get_thread_name(thread)));
2493       JvmtiMonitorEventMark  jem(thread, h());
2494       JvmtiEnv *env = ets->get_env();
2495       JvmtiThreadEventTransition jet(thread);
2496       jvmtiEventMonitorWaited callback = env->callbacks()->MonitorWaited;
2497       if (callback != NULL) {
2498         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2499                     jem.jni_object(), timed_out);
2500       }
2501     }
2502   }
2503 }
2504 
2505 void JvmtiExport::post_vm_object_alloc(JavaThread *thread, oop object) {
2506   EVT_TRIG_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Trg vm object alloc triggered",
2507                       JvmtiTrace::safe_get_thread_name(thread)));
2508   if (object == NULL) {
2509     return;
2510   }



2511   HandleMark hm(thread);
2512   Handle h(thread, object);
2513   JvmtiEnvIterator it;
2514   for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
2515     if (env->is_enabled(JVMTI_EVENT_VM_OBJECT_ALLOC)) {
2516       EVT_TRACE(JVMTI_EVENT_VM_OBJECT_ALLOC, ("[%s] Evt vmobject alloc sent %s",
2517                                          JvmtiTrace::safe_get_thread_name(thread),
2518                                          object==NULL? "NULL" : object->klass()->external_name()));
2519 
2520       JvmtiObjectAllocEventMark jem(thread, h());
2521       JvmtiJavaThreadEventTransition jet(thread);
2522       jvmtiEventVMObjectAlloc callback = env->callbacks()->VMObjectAlloc;
2523       if (callback != NULL) {
2524         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2525                     jem.jni_jobject(), jem.jni_class(), jem.size());
2526       }
2527     }
2528   }
2529 }
2530 
2531 void JvmtiExport::post_sampled_object_alloc(JavaThread *thread, oop object) {
2532   JvmtiThreadState *state = thread->jvmti_thread_state();
2533   if (state == NULL) {
2534     return;
2535   }
2536 
2537   EVT_TRIG_TRACE(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC,
2538                  ("[%s] Trg sampled object alloc triggered",
2539                   JvmtiTrace::safe_get_thread_name(thread)));
2540   if (object == NULL) {
2541     return;
2542   }



2543   HandleMark hm(thread);
2544   Handle h(thread, object);
2545 
2546   JvmtiEnvThreadStateIterator it(state);
2547   for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) {
2548     if (ets->is_enabled(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC)) {
2549       EVT_TRACE(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC,
2550                 ("[%s] Evt sampled object alloc sent %s",
2551                  JvmtiTrace::safe_get_thread_name(thread),
2552                  object == NULL ? "NULL" : object->klass()->external_name()));
2553 
2554       JvmtiEnv *env = ets->get_env();
2555       JvmtiObjectAllocEventMark jem(thread, h());
2556       JvmtiJavaThreadEventTransition jet(thread);
2557       jvmtiEventSampledObjectAlloc callback = env->callbacks()->SampledObjectAlloc;
2558       if (callback != NULL) {
2559         (*callback)(env->jvmti_external(), jem.jni_env(), jem.jni_thread(),
2560                     jem.jni_jobject(), jem.jni_class(), jem.size());
2561       }
2562     }
2563   }
2564 }
2565 
2566 ////////////////////////////////////////////////////////////////////////////////////////////////
2567 
2568 void JvmtiExport::cleanup_thread(JavaThread* thread) {
2569   assert(JavaThread::current() == thread, "thread is not current");
2570   MutexLocker mu(thread, JvmtiThreadState_lock);
2571 
2572   if (thread->jvmti_thread_state() != NULL) {
2573     // This has to happen after the thread state is removed, which is
2574     // why it is not in post_thread_end_event like its complement
2575     // Maybe both these functions should be rolled into the posts?
2576     JvmtiEventController::thread_ended(thread);
2577   }
2578 }
2579 
2580 void JvmtiExport::clear_detected_exception(JavaThread* thread) {
2581   assert(JavaThread::current() == thread, "thread is not current");
2582 
2583   JvmtiThreadState* state = thread->jvmti_thread_state();
2584   if (state != NULL) {
2585     state->clear_exception_state();
2586   }
2587 }
2588 
2589 // Onload raw monitor transition.
2590 void JvmtiExport::transition_pending_onload_raw_monitors() {
2591   JvmtiPendingMonitors::transition_raw_monitors();
2592 }
2593 
2594 ////////////////////////////////////////////////////////////////////////////////////////////////
2595 #if INCLUDE_SERVICES
2596 // Attach is disabled if SERVICES is not included
2597 
2598 // type for the Agent_OnAttach entry point
2599 extern "C" {
2600   typedef jint (JNICALL *OnAttachEntry_t)(JavaVM*, char *, void *);
2601 }
2602 
2603 jint JvmtiExport::load_agent_library(const char *agent, const char *absParam,
2604                                      const char *options, outputStream* st) {
2605   char ebuf[1024] = {0};
2606   char buffer[JVM_MAXPATHLEN];
2607   void* library = NULL;
2608   jint result = JNI_ERR;
2609   const char *on_attach_symbols[] = AGENT_ONATTACH_SYMBOLS;
2610   size_t num_symbol_entries = ARRAY_SIZE(on_attach_symbols);
2611 
2612   // The abs paramter should be "true" or "false"
2613   bool is_absolute_path = (absParam != NULL) && (strcmp(absParam,"true")==0);
2614 
2615   // Initially marked as invalid. It will be set to valid if we can find the agent
2616   AgentLibrary *agent_lib = new AgentLibrary(agent, options, is_absolute_path, NULL);
2617 
2618   // Check for statically linked in agent. If not found then if the path is
2619   // absolute we attempt to load the library. Otherwise we try to load it
2620   // from the standard dll directory.
2621 
2622   if (!os::find_builtin_agent(agent_lib, on_attach_symbols, num_symbol_entries)) {
2623     if (is_absolute_path) {
2624       library = os::dll_load(agent, ebuf, sizeof ebuf);
2625     } else {
2626       // Try to load the agent from the standard dll directory
2627       if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
2628                              agent)) {
2629         library = os::dll_load(buffer, ebuf, sizeof ebuf);
2630       }
2631       if (library == NULL) {
2632         // not found - try OS default library path
2633         if (os::dll_build_name(buffer, sizeof(buffer), agent)) {
2634           library = os::dll_load(buffer, ebuf, sizeof ebuf);
2635         }
2636       }
2637     }
2638     if (library != NULL) {
2639       agent_lib->set_os_lib(library);
2640       agent_lib->set_valid();
2641     }
2642   }
2643   // If the library was loaded then we attempt to invoke the Agent_OnAttach
2644   // function
2645   if (agent_lib->valid()) {
2646     // Lookup the Agent_OnAttach function
2647     OnAttachEntry_t on_attach_entry = NULL;
2648     on_attach_entry = CAST_TO_FN_PTR(OnAttachEntry_t,
2649        os::find_agent_function(agent_lib, false, on_attach_symbols, num_symbol_entries));
2650     if (on_attach_entry == NULL) {
2651       // Agent_OnAttach missing - unload library
2652       if (!agent_lib->is_static_lib()) {
2653         os::dll_unload(library);
2654       }
2655       st->print_cr("%s is not available in %s",
2656                    on_attach_symbols[0], agent_lib->name());
2657       delete agent_lib;
2658     } else {
2659       // Invoke the Agent_OnAttach function
2660       JavaThread* THREAD = JavaThread::current(); // For exception macros.
2661       {
2662         extern struct JavaVM_ main_vm;
2663         JvmtiThreadEventMark jem(THREAD);
2664         JvmtiJavaThreadEventTransition jet(THREAD);
2665 
2666         result = (*on_attach_entry)(&main_vm, (char*)options, NULL);
2667       }
2668 
2669       // Agent_OnAttach may have used JNI
2670       if (HAS_PENDING_EXCEPTION) {
2671         CLEAR_PENDING_EXCEPTION;
2672       }
2673 
2674       // If OnAttach returns JNI_OK then we add it to the list of
2675       // agent libraries so that we can call Agent_OnUnload later.
2676       if (result == JNI_OK) {
2677         Arguments::add_loaded_agent(agent_lib);
2678       } else {
2679         if (!agent_lib->is_static_lib()) {
2680           os::dll_unload(library);
2681         }
2682         delete agent_lib;
2683       }
2684 
2685       // Agent_OnAttach executed so completion status is JNI_OK
2686       st->print_cr("return code: %d", result);
2687       result = JNI_OK;
2688     }
2689   } else {
2690     st->print_cr("%s was not loaded.", agent);
2691     if (*ebuf != '\0') {
2692       st->print_cr("%s", ebuf);
2693     }
2694   }
2695   return result;
2696 }
2697 
2698 #endif // INCLUDE_SERVICES
2699 ////////////////////////////////////////////////////////////////////////////////////////////////
2700 
2701 // Setup current current thread for event collection.
2702 void JvmtiEventCollector::setup_jvmti_thread_state() {
2703   // set this event collector to be the current one.
2704   JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
2705   // state can only be NULL if the current thread is exiting which
2706   // should not happen since we're trying to configure for event collection
2707   guarantee(state != NULL, "exiting thread called setup_jvmti_thread_state");
2708   if (is_vm_object_alloc_event()) {
2709     JvmtiVMObjectAllocEventCollector *prev = state->get_vm_object_alloc_event_collector();
2710 
2711     // If we have a previous collector and it is disabled, it means this allocation came from a
2712     // callback induced VM Object allocation, do not register this collector then.
2713     if (prev && !prev->is_enabled()) {
2714       return;
2715     }
2716     _prev = prev;
2717     state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)this);
2718   } else if (is_dynamic_code_event()) {
2719     _prev = state->get_dynamic_code_event_collector();
2720     state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)this);
2721   } else if (is_sampled_object_alloc_event()) {
2722     JvmtiSampledObjectAllocEventCollector *prev = state->get_sampled_object_alloc_event_collector();
2723 
2724     if (prev) {
2725       // JvmtiSampledObjectAllocEventCollector wants only one active collector
2726       // enabled. This allows to have a collector detect a user code requiring
2727       // a sample in the callback.
2728       return;
2729     }
2730     state->set_sampled_object_alloc_event_collector((JvmtiSampledObjectAllocEventCollector*) this);
2731   }
2732 
2733   _unset_jvmti_thread_state = true;
2734 }
2735 
2736 // Unset current event collection in this thread and reset it with previous
2737 // collector.
2738 void JvmtiEventCollector::unset_jvmti_thread_state() {
2739   if (!_unset_jvmti_thread_state) {
2740     return;
2741   }
2742 
2743   JvmtiThreadState* state = JavaThread::current()->jvmti_thread_state();
2744   if (state != NULL) {
2745     // restore the previous event collector (if any)
2746     if (is_vm_object_alloc_event()) {
2747       if (state->get_vm_object_alloc_event_collector() == this) {
2748         state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)_prev);
2749       } else {
2750         // this thread's jvmti state was created during the scope of
2751         // the event collector.
2752       }
2753     } else if (is_dynamic_code_event()) {
2754       if (state->get_dynamic_code_event_collector() == this) {
2755         state->set_dynamic_code_event_collector((JvmtiDynamicCodeEventCollector *)_prev);
2756       } else {
2757         // this thread's jvmti state was created during the scope of
2758         // the event collector.
2759       }
2760     } else if (is_sampled_object_alloc_event()) {
2761       if (state->get_sampled_object_alloc_event_collector() == this) {
2762         state->set_sampled_object_alloc_event_collector((JvmtiSampledObjectAllocEventCollector*)_prev);
2763       } else {
2764         // this thread's jvmti state was created during the scope of
2765         // the event collector.
2766       }
2767     }
2768   }
2769 }
2770 
2771 // create the dynamic code event collector
2772 JvmtiDynamicCodeEventCollector::JvmtiDynamicCodeEventCollector() : _code_blobs(NULL) {
2773   if (JvmtiExport::should_post_dynamic_code_generated()) {
2774     setup_jvmti_thread_state();
2775   }
2776 }
2777 
2778 // iterate over any code blob descriptors collected and post a
2779 // DYNAMIC_CODE_GENERATED event to the profiler.
2780 JvmtiDynamicCodeEventCollector::~JvmtiDynamicCodeEventCollector() {
2781   assert(!JavaThread::current()->owns_locks(), "all locks must be released to post deferred events");
2782  // iterate over any code blob descriptors that we collected
2783  if (_code_blobs != NULL) {
2784    for (int i=0; i<_code_blobs->length(); i++) {
2785      JvmtiCodeBlobDesc* blob = _code_blobs->at(i);
2786      JvmtiExport::post_dynamic_code_generated(blob->name(), blob->code_begin(), blob->code_end());
2787      FreeHeap(blob);
2788    }
2789    delete _code_blobs;
2790  }
2791  unset_jvmti_thread_state();
2792 }
2793 
2794 // register a stub
2795 void JvmtiDynamicCodeEventCollector::register_stub(const char* name, address start, address end) {
2796  if (_code_blobs == NULL) {
2797    _code_blobs = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<JvmtiCodeBlobDesc*>(1, mtServiceability);
2798  }
2799  _code_blobs->append(new JvmtiCodeBlobDesc(name, start, end));
2800 }
2801 
2802 // Setup current thread to record vm allocated objects.
2803 JvmtiObjectAllocEventCollector::JvmtiObjectAllocEventCollector() :
2804     _allocated(NULL), _enable(false), _post_callback(NULL) {
2805 }
2806 
2807 // Post vm_object_alloc event for vm allocated objects visible to java
2808 // world.
2809 void JvmtiObjectAllocEventCollector::generate_call_for_allocated() {
2810   if (_allocated) {
2811     set_enabled(false);
2812     for (int i = 0; i < _allocated->length(); i++) {
2813       oop obj = _allocated->at(i).resolve();
2814       _post_callback(JavaThread::current(), obj);
2815       // Release OopHandle
2816       _allocated->at(i).release(JvmtiExport::jvmti_oop_storage());
2817 
2818     }
2819     delete _allocated, _allocated = NULL;
2820   }
2821 }
2822 
2823 void JvmtiObjectAllocEventCollector::record_allocation(oop obj) {
2824   assert(is_enabled(), "Object alloc event collector is not enabled");
2825   if (_allocated == NULL) {
2826     _allocated = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<OopHandle>(1, mtServiceability);
2827   }
2828   _allocated->push(OopHandle(JvmtiExport::jvmti_oop_storage(), obj));
2829 }
2830 
2831 // Disable collection of VMObjectAlloc events
2832 NoJvmtiVMObjectAllocMark::NoJvmtiVMObjectAllocMark() : _collector(NULL) {
2833   // a no-op if VMObjectAlloc event is not enabled
2834   if (!JvmtiExport::should_post_vm_object_alloc()) {
2835     return;
2836   }
2837   Thread* thread = Thread::current_or_null();
2838   if (thread != NULL && thread->is_Java_thread())  {
2839     JavaThread* current_thread = JavaThread::cast(thread);
2840     JvmtiThreadState *state = current_thread->jvmti_thread_state();
2841     if (state != NULL) {
2842       JvmtiVMObjectAllocEventCollector *collector;
2843       collector = state->get_vm_object_alloc_event_collector();
2844       if (collector != NULL && collector->is_enabled()) {
2845         _collector = collector;
2846         _collector->set_enabled(false);
2847       }
2848     }
2849   }
2850 }
2851 
2852 // Re-Enable collection of VMObjectAlloc events (if previously enabled)
2853 NoJvmtiVMObjectAllocMark::~NoJvmtiVMObjectAllocMark() {
2854   if (was_enabled()) {
2855     _collector->set_enabled(true);
2856   }
2857 };
2858 
2859 // Setup current thread to record vm allocated objects.
2860 JvmtiVMObjectAllocEventCollector::JvmtiVMObjectAllocEventCollector() {
2861   if (JvmtiExport::should_post_vm_object_alloc()) {
2862     _enable = true;
2863     setup_jvmti_thread_state();
2864     _post_callback = JvmtiExport::post_vm_object_alloc;
2865   }
2866 }
2867 
2868 JvmtiVMObjectAllocEventCollector::~JvmtiVMObjectAllocEventCollector() {
2869   if (_enable) {
2870     generate_call_for_allocated();
2871   }
2872   unset_jvmti_thread_state();
2873 }
2874 
2875 bool JvmtiSampledObjectAllocEventCollector::object_alloc_is_safe_to_sample() {
2876   Thread* thread = Thread::current();
2877   // Really only sample allocations if this is a JavaThread and not the compiler
2878   // thread.
2879   if (!thread->is_Java_thread() || thread->is_Compiler_thread()) {
2880     return false;
2881   }
2882 
2883   if (MultiArray_lock->owner() == thread) {
2884     return false;
2885   }
2886   return true;
2887 }
2888 
2889 // Setup current thread to record sampled allocated objects.
2890 JvmtiSampledObjectAllocEventCollector::JvmtiSampledObjectAllocEventCollector() {
2891   if (JvmtiExport::should_post_sampled_object_alloc()) {
2892     if (!object_alloc_is_safe_to_sample()) {
2893       return;
2894     }
2895 
2896     _enable = true;
2897     setup_jvmti_thread_state();
2898     _post_callback = JvmtiExport::post_sampled_object_alloc;
2899   }
2900 }
2901 
2902 JvmtiSampledObjectAllocEventCollector::~JvmtiSampledObjectAllocEventCollector() {
2903   if (!_enable) {
2904     return;
2905   }
2906 
2907   generate_call_for_allocated();
2908   unset_jvmti_thread_state();
2909 
2910   // Unset the sampling collector as present in assertion mode only.
2911   assert(Thread::current()->is_Java_thread(),
2912          "Should always be in a Java thread");
2913 }
2914 
2915 JvmtiGCMarker::JvmtiGCMarker() {
2916   // if there aren't any JVMTI environments then nothing to do
2917   if (!JvmtiEnv::environments_might_exist()) {
2918     return;
2919   }
2920 
2921   if (JvmtiExport::should_post_garbage_collection_start()) {
2922     JvmtiExport::post_garbage_collection_start();
2923   }
2924 
2925   if (SafepointSynchronize::is_at_safepoint()) {
2926     // Do clean up tasks that need to be done at a safepoint
2927     JvmtiEnvBase::check_for_periodic_clean_up();
2928   }
2929 }
2930 
2931 JvmtiGCMarker::~JvmtiGCMarker() {
2932   // if there aren't any JVMTI environments then nothing to do
2933   if (!JvmtiEnv::environments_might_exist()) {
2934     return;
2935   }
2936 
2937   // JVMTI notify gc finish
2938   if (JvmtiExport::should_post_garbage_collection_finish()) {
2939     JvmtiExport::post_garbage_collection_finish();
2940   }
2941 }
--- EOF ---