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