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