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