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