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