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