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