Thu, 09 Dec 2010 15:04:26 -0500
7004582: Add GetThisObject() function to JVMTI 1.2
Summary: Add 'GetThisObject' function
Reviewed-by: never, coleenp
1 /*
2 * Copyright (c) 2003, 2010, 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 */
25 #include "precompiled.hpp"
26 #include "classfile/systemDictionary.hpp"
27 #include "jvmtifiles/jvmtiEnv.hpp"
28 #include "oops/objArrayKlass.hpp"
29 #include "oops/objArrayOop.hpp"
30 #include "prims/jvmtiEnvBase.hpp"
31 #include "prims/jvmtiEventController.inline.hpp"
32 #include "prims/jvmtiExtensions.hpp"
33 #include "prims/jvmtiImpl.hpp"
34 #include "prims/jvmtiManageCapabilities.hpp"
35 #include "prims/jvmtiTagMap.hpp"
36 #include "prims/jvmtiThreadState.inline.hpp"
37 #include "runtime/biasedLocking.hpp"
38 #include "runtime/deoptimization.hpp"
39 #include "runtime/interfaceSupport.hpp"
40 #include "runtime/jfieldIDWorkaround.hpp"
41 #include "runtime/objectMonitor.hpp"
42 #include "runtime/objectMonitor.inline.hpp"
43 #include "runtime/signature.hpp"
44 #include "runtime/vframe.hpp"
45 #include "runtime/vframe_hp.hpp"
46 #include "runtime/vmThread.hpp"
47 #include "runtime/vm_operations.hpp"
49 ///////////////////////////////////////////////////////////////
50 //
51 // JvmtiEnvBase
52 //
54 JvmtiEnvBase* JvmtiEnvBase::_head_environment = NULL;
56 bool JvmtiEnvBase::_globally_initialized = false;
57 volatile bool JvmtiEnvBase::_needs_clean_up = false;
59 jvmtiPhase JvmtiEnvBase::_phase = JVMTI_PHASE_PRIMORDIAL;
61 volatile int JvmtiEnvBase::_dying_thread_env_iteration_count = 0;
63 extern jvmtiInterface_1_ jvmti_Interface;
64 extern jvmtiInterface_1_ jvmtiTrace_Interface;
67 // perform initializations that must occur before any JVMTI environments
68 // are released but which should only be initialized once (no matter
69 // how many environments are created).
70 void
71 JvmtiEnvBase::globally_initialize() {
72 assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
73 assert(_globally_initialized == false, "bad call");
75 JvmtiManageCapabilities::initialize();
77 #ifndef JVMTI_KERNEL
78 // register extension functions and events
79 JvmtiExtensions::register_extensions();
80 #endif // !JVMTI_KERNEL
82 #ifdef JVMTI_TRACE
83 JvmtiTrace::initialize();
84 #endif
86 _globally_initialized = true;
87 }
90 void
91 JvmtiEnvBase::initialize() {
92 assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
94 // Add this environment to the end of the environment list (order is important)
95 {
96 // This block of code must not contain any safepoints, as list deallocation
97 // (which occurs at a safepoint) cannot occur simultaneously with this list
98 // addition. Note: No_Safepoint_Verifier cannot, currently, be used before
99 // threads exist.
100 JvmtiEnvIterator it;
101 JvmtiEnvBase *previous_env = NULL;
102 for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
103 previous_env = env;
104 }
105 if (previous_env == NULL) {
106 _head_environment = this;
107 } else {
108 previous_env->set_next_environment(this);
109 }
110 }
112 if (_globally_initialized == false) {
113 globally_initialize();
114 }
115 }
118 bool
119 JvmtiEnvBase::is_valid() {
120 jint value = 0;
122 // This object might not be a JvmtiEnvBase so we can't assume
123 // the _magic field is properly aligned. Get the value in a safe
124 // way and then check against JVMTI_MAGIC.
126 switch (sizeof(_magic)) {
127 case 2:
128 value = Bytes::get_native_u2((address)&_magic);
129 break;
131 case 4:
132 value = Bytes::get_native_u4((address)&_magic);
133 break;
135 case 8:
136 value = Bytes::get_native_u8((address)&_magic);
137 break;
139 default:
140 guarantee(false, "_magic field is an unexpected size");
141 }
143 return value == JVMTI_MAGIC;
144 }
147 bool
148 JvmtiEnvBase::use_version_1_0_semantics() {
149 int major, minor, micro;
151 JvmtiExport::decode_version_values(_version, &major, &minor, µ);
152 return major == 1 && minor == 0; // micro version doesn't matter here
153 }
156 bool
157 JvmtiEnvBase::use_version_1_1_semantics() {
158 int major, minor, micro;
160 JvmtiExport::decode_version_values(_version, &major, &minor, µ);
161 return major == 1 && minor == 1; // micro version doesn't matter here
162 }
164 bool
165 JvmtiEnvBase::use_version_1_2_semantics() {
166 int major, minor, micro;
168 JvmtiExport::decode_version_values(_version, &major, &minor, µ);
169 return major == 1 && minor == 2; // micro version doesn't matter here
170 }
173 JvmtiEnvBase::JvmtiEnvBase(jint version) : _env_event_enable() {
174 _version = version;
175 _env_local_storage = NULL;
176 _tag_map = NULL;
177 _native_method_prefix_count = 0;
178 _native_method_prefixes = NULL;
179 _next = NULL;
180 _class_file_load_hook_ever_enabled = false;
182 // Moot since ClassFileLoadHook not yet enabled.
183 // But "true" will give a more predictable ClassFileLoadHook behavior
184 // for environment creation during ClassFileLoadHook.
185 _is_retransformable = true;
187 // all callbacks initially NULL
188 memset(&_event_callbacks,0,sizeof(jvmtiEventCallbacks));
190 // all capabilities initially off
191 memset(&_current_capabilities, 0, sizeof(_current_capabilities));
193 // all prohibited capabilities initially off
194 memset(&_prohibited_capabilities, 0, sizeof(_prohibited_capabilities));
196 _magic = JVMTI_MAGIC;
198 JvmtiEventController::env_initialize((JvmtiEnv*)this);
200 #ifdef JVMTI_TRACE
201 _jvmti_external.functions = TraceJVMTI != NULL ? &jvmtiTrace_Interface : &jvmti_Interface;
202 #else
203 _jvmti_external.functions = &jvmti_Interface;
204 #endif
205 }
208 void
209 JvmtiEnvBase::dispose() {
211 #ifdef JVMTI_TRACE
212 JvmtiTrace::shutdown();
213 #endif
215 // Dispose of event info and let the event controller call us back
216 // in a locked state (env_dispose, below)
217 JvmtiEventController::env_dispose(this);
218 }
220 void
221 JvmtiEnvBase::env_dispose() {
222 assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
224 // We have been entered with all events disabled on this environment.
225 // A race to re-enable events (by setting callbacks) is prevented by
226 // checking for a valid environment when setting callbacks (while
227 // holding the JvmtiThreadState_lock).
229 // Mark as invalid.
230 _magic = DISPOSED_MAGIC;
232 // Relinquish all capabilities.
233 jvmtiCapabilities *caps = get_capabilities();
234 JvmtiManageCapabilities::relinquish_capabilities(caps, caps, caps);
236 // Same situation as with events (see above)
237 set_native_method_prefixes(0, NULL);
239 #ifndef JVMTI_KERNEL
240 JvmtiTagMap* tag_map_to_deallocate = _tag_map;
241 set_tag_map(NULL);
242 // A tag map can be big, deallocate it now
243 if (tag_map_to_deallocate != NULL) {
244 delete tag_map_to_deallocate;
245 }
246 #endif // !JVMTI_KERNEL
248 _needs_clean_up = true;
249 }
252 JvmtiEnvBase::~JvmtiEnvBase() {
253 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
255 // There is a small window of time during which the tag map of a
256 // disposed environment could have been reallocated.
257 // Make sure it is gone.
258 #ifndef JVMTI_KERNEL
259 JvmtiTagMap* tag_map_to_deallocate = _tag_map;
260 set_tag_map(NULL);
261 // A tag map can be big, deallocate it now
262 if (tag_map_to_deallocate != NULL) {
263 delete tag_map_to_deallocate;
264 }
265 #endif // !JVMTI_KERNEL
267 _magic = BAD_MAGIC;
268 }
271 void
272 JvmtiEnvBase::periodic_clean_up() {
273 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
275 // JvmtiEnvBase reference is saved in JvmtiEnvThreadState. So
276 // clean up JvmtiThreadState before deleting JvmtiEnv pointer.
277 JvmtiThreadState::periodic_clean_up();
279 // Unlink all invalid environments from the list of environments
280 // and deallocate them
281 JvmtiEnvIterator it;
282 JvmtiEnvBase* previous_env = NULL;
283 JvmtiEnvBase* env = it.first();
284 while (env != NULL) {
285 if (env->is_valid()) {
286 previous_env = env;
287 env = it.next(env);
288 } else {
289 // This one isn't valid, remove it from the list and deallocate it
290 JvmtiEnvBase* defunct_env = env;
291 env = it.next(env);
292 if (previous_env == NULL) {
293 _head_environment = env;
294 } else {
295 previous_env->set_next_environment(env);
296 }
297 delete defunct_env;
298 }
299 }
301 }
304 void
305 JvmtiEnvBase::check_for_periodic_clean_up() {
306 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
308 class ThreadInsideIterationClosure: public ThreadClosure {
309 private:
310 bool _inside;
311 public:
312 ThreadInsideIterationClosure() : _inside(false) {};
314 void do_thread(Thread* thread) {
315 _inside |= thread->is_inside_jvmti_env_iteration();
316 }
318 bool is_inside_jvmti_env_iteration() {
319 return _inside;
320 }
321 };
323 if (_needs_clean_up) {
324 // Check if we are currently iterating environment,
325 // deallocation should not occur if we are
326 ThreadInsideIterationClosure tiic;
327 Threads::threads_do(&tiic);
328 if (!tiic.is_inside_jvmti_env_iteration() &&
329 !is_inside_dying_thread_env_iteration()) {
330 _needs_clean_up = false;
331 JvmtiEnvBase::periodic_clean_up();
332 }
333 }
334 }
337 void
338 JvmtiEnvBase::record_first_time_class_file_load_hook_enabled() {
339 assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
340 "sanity check");
342 if (!_class_file_load_hook_ever_enabled) {
343 _class_file_load_hook_ever_enabled = true;
345 if (get_capabilities()->can_retransform_classes) {
346 _is_retransformable = true;
347 } else {
348 _is_retransformable = false;
350 // cannot add retransform capability after ClassFileLoadHook has been enabled
351 get_prohibited_capabilities()->can_retransform_classes = 1;
352 }
353 }
354 }
357 void
358 JvmtiEnvBase::record_class_file_load_hook_enabled() {
359 if (!_class_file_load_hook_ever_enabled) {
360 if (Threads::number_of_threads() == 0) {
361 record_first_time_class_file_load_hook_enabled();
362 } else {
363 MutexLocker mu(JvmtiThreadState_lock);
364 record_first_time_class_file_load_hook_enabled();
365 }
366 }
367 }
370 jvmtiError
371 JvmtiEnvBase::set_native_method_prefixes(jint prefix_count, char** prefixes) {
372 assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
373 "sanity check");
375 int old_prefix_count = get_native_method_prefix_count();
376 char **old_prefixes = get_native_method_prefixes();
378 // allocate and install the new prefixex
379 if (prefix_count == 0 || !is_valid()) {
380 _native_method_prefix_count = 0;
381 _native_method_prefixes = NULL;
382 } else {
383 // there are prefixes, allocate an array to hold them, and fill it
384 char** new_prefixes = (char**)os::malloc((prefix_count) * sizeof(char*));
385 if (new_prefixes == NULL) {
386 return JVMTI_ERROR_OUT_OF_MEMORY;
387 }
388 for (int i = 0; i < prefix_count; i++) {
389 char* prefix = prefixes[i];
390 if (prefix == NULL) {
391 for (int j = 0; j < (i-1); j++) {
392 os::free(new_prefixes[j]);
393 }
394 os::free(new_prefixes);
395 return JVMTI_ERROR_NULL_POINTER;
396 }
397 prefix = os::strdup(prefixes[i]);
398 if (prefix == NULL) {
399 for (int j = 0; j < (i-1); j++) {
400 os::free(new_prefixes[j]);
401 }
402 os::free(new_prefixes);
403 return JVMTI_ERROR_OUT_OF_MEMORY;
404 }
405 new_prefixes[i] = prefix;
406 }
407 _native_method_prefix_count = prefix_count;
408 _native_method_prefixes = new_prefixes;
409 }
411 // now that we know the new prefixes have been successfully installed we can
412 // safely remove the old ones
413 if (old_prefix_count != 0) {
414 for (int i = 0; i < old_prefix_count; i++) {
415 os::free(old_prefixes[i]);
416 }
417 os::free(old_prefixes);
418 }
420 return JVMTI_ERROR_NONE;
421 }
424 // Collect all the prefixes which have been set in any JVM TI environments
425 // by the SetNativeMethodPrefix(es) functions. Be sure to maintain the
426 // order of environments and the order of prefixes within each environment.
427 // Return in a resource allocated array.
428 char**
429 JvmtiEnvBase::get_all_native_method_prefixes(int* count_ptr) {
430 assert(Threads::number_of_threads() == 0 ||
431 SafepointSynchronize::is_at_safepoint() ||
432 JvmtiThreadState_lock->is_locked(),
433 "sanity check");
435 int total_count = 0;
436 GrowableArray<char*>* prefix_array =new GrowableArray<char*>(5);
438 JvmtiEnvIterator it;
439 for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
440 int prefix_count = env->get_native_method_prefix_count();
441 char** prefixes = env->get_native_method_prefixes();
442 for (int j = 0; j < prefix_count; j++) {
443 // retrieve a prefix and so that it is safe against asynchronous changes
444 // copy it into the resource area
445 char* prefix = prefixes[j];
446 char* prefix_copy = NEW_RESOURCE_ARRAY(char, strlen(prefix)+1);
447 strcpy(prefix_copy, prefix);
448 prefix_array->at_put_grow(total_count++, prefix_copy);
449 }
450 }
452 char** all_prefixes = NEW_RESOURCE_ARRAY(char*, total_count);
453 char** p = all_prefixes;
454 for (int i = 0; i < total_count; ++i) {
455 *p++ = prefix_array->at(i);
456 }
457 *count_ptr = total_count;
458 return all_prefixes;
459 }
461 void
462 JvmtiEnvBase::set_event_callbacks(const jvmtiEventCallbacks* callbacks,
463 jint size_of_callbacks) {
464 assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
466 size_t byte_cnt = sizeof(jvmtiEventCallbacks);
468 // clear in either case to be sure we got any gap between sizes
469 memset(&_event_callbacks, 0, byte_cnt);
471 // Now that JvmtiThreadState_lock is held, prevent a possible race condition where events
472 // are re-enabled by a call to set event callbacks where the DisposeEnvironment
473 // occurs after the boiler-plate environment check and before the lock is acquired.
474 if (callbacks != NULL && is_valid()) {
475 if (size_of_callbacks < (jint)byte_cnt) {
476 byte_cnt = size_of_callbacks;
477 }
478 memcpy(&_event_callbacks, callbacks, byte_cnt);
479 }
480 }
482 // Called from JVMTI entry points which perform stack walking. If the
483 // associated JavaThread is the current thread, then wait_for_suspend
484 // is not used. Otherwise, it determines if we should wait for the
485 // "other" thread to complete external suspension. (NOTE: in future
486 // releases the suspension mechanism should be reimplemented so this
487 // is not necessary.)
488 //
489 bool
490 JvmtiEnvBase::is_thread_fully_suspended(JavaThread* thr, bool wait_for_suspend, uint32_t *bits) {
491 // "other" threads require special handling
492 if (thr != JavaThread::current()) {
493 if (wait_for_suspend) {
494 // We are allowed to wait for the external suspend to complete
495 // so give the other thread a chance to get suspended.
496 if (!thr->wait_for_ext_suspend_completion(SuspendRetryCount,
497 SuspendRetryDelay, bits)) {
498 // didn't make it so let the caller know
499 return false;
500 }
501 }
502 // We aren't allowed to wait for the external suspend to complete
503 // so if the other thread isn't externally suspended we need to
504 // let the caller know.
505 else if (!thr->is_ext_suspend_completed_with_lock(bits)) {
506 return false;
507 }
508 }
510 return true;
511 }
514 // In the fullness of time, all users of the method should instead
515 // directly use allocate, besides being cleaner and faster, this will
516 // mean much better out of memory handling
517 unsigned char *
518 JvmtiEnvBase::jvmtiMalloc(jlong size) {
519 unsigned char* mem;
520 jvmtiError result = allocate(size, &mem);
521 assert(result == JVMTI_ERROR_NONE, "Allocate failed");
522 return mem;
523 }
526 //
527 // Threads
528 //
530 jobject *
531 JvmtiEnvBase::new_jobjectArray(int length, Handle *handles) {
532 if (length == 0) {
533 return NULL;
534 }
536 jobject *objArray = (jobject *) jvmtiMalloc(sizeof(jobject) * length);
537 NULL_CHECK(objArray, NULL);
539 for (int i=0; i<length; i++) {
540 objArray[i] = jni_reference(handles[i]);
541 }
542 return objArray;
543 }
545 jthread *
546 JvmtiEnvBase::new_jthreadArray(int length, Handle *handles) {
547 return (jthread *) new_jobjectArray(length,handles);
548 }
550 jthreadGroup *
551 JvmtiEnvBase::new_jthreadGroupArray(int length, Handle *handles) {
552 return (jthreadGroup *) new_jobjectArray(length,handles);
553 }
556 JavaThread *
557 JvmtiEnvBase::get_JavaThread(jthread jni_thread) {
558 oop t = JNIHandles::resolve_external_guard(jni_thread);
559 if (t == NULL || !t->is_a(SystemDictionary::Thread_klass())) {
560 return NULL;
561 }
562 // The following returns NULL if the thread has not yet run or is in
563 // process of exiting
564 return java_lang_Thread::thread(t);
565 }
568 // update the access_flags for the field in the klass
569 void
570 JvmtiEnvBase::update_klass_field_access_flag(fieldDescriptor *fd) {
571 instanceKlass* ik = instanceKlass::cast(fd->field_holder());
572 typeArrayOop fields = ik->fields();
573 fields->ushort_at_put(fd->index(), (jushort)fd->access_flags().as_short());
574 }
577 // return the vframe on the specified thread and depth, NULL if no such frame
578 vframe*
579 JvmtiEnvBase::vframeFor(JavaThread* java_thread, jint depth) {
580 if (!java_thread->has_last_Java_frame()) {
581 return NULL;
582 }
583 RegisterMap reg_map(java_thread);
584 vframe *vf = java_thread->last_java_vframe(®_map);
585 int d = 0;
586 while ((vf != NULL) && (d < depth)) {
587 vf = vf->java_sender();
588 d++;
589 }
590 return vf;
591 }
594 //
595 // utilities: JNI objects
596 //
599 jclass
600 JvmtiEnvBase::get_jni_class_non_null(klassOop k) {
601 assert(k != NULL, "k != NULL");
602 return (jclass)jni_reference(Klass::cast(k)->java_mirror());
603 }
605 #ifndef JVMTI_KERNEL
607 //
608 // Field Information
609 //
611 bool
612 JvmtiEnvBase::get_field_descriptor(klassOop k, jfieldID field, fieldDescriptor* fd) {
613 if (!jfieldIDWorkaround::is_valid_jfieldID(k, field)) {
614 return false;
615 }
616 bool found = false;
617 if (jfieldIDWorkaround::is_static_jfieldID(field)) {
618 JNIid* id = jfieldIDWorkaround::from_static_jfieldID(field);
619 int offset = id->offset();
620 klassOop holder = id->holder();
621 found = instanceKlass::cast(holder)->find_local_field_from_offset(offset, true, fd);
622 } else {
623 // Non-static field. The fieldID is really the offset of the field within the object.
624 int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);
625 found = instanceKlass::cast(k)->find_field_from_offset(offset, false, fd);
626 }
627 return found;
628 }
630 //
631 // Object Monitor Information
632 //
634 //
635 // Count the number of objects for a lightweight monitor. The hobj
636 // parameter is object that owns the monitor so this routine will
637 // count the number of times the same object was locked by frames
638 // in java_thread.
639 //
640 jint
641 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
642 jint ret = 0;
643 if (!java_thread->has_last_Java_frame()) {
644 return ret; // no Java frames so no monitors
645 }
647 ResourceMark rm;
648 HandleMark hm;
649 RegisterMap reg_map(java_thread);
651 for(javaVFrame *jvf=java_thread->last_java_vframe(®_map); jvf != NULL;
652 jvf = jvf->java_sender()) {
653 GrowableArray<MonitorInfo*>* mons = jvf->monitors();
654 if (!mons->is_empty()) {
655 for (int i = 0; i < mons->length(); i++) {
656 MonitorInfo *mi = mons->at(i);
657 if (mi->owner_is_scalar_replaced()) continue;
659 // see if owner of the monitor is our object
660 if (mi->owner() != NULL && mi->owner() == hobj()) {
661 ret++;
662 }
663 }
664 }
665 }
666 return ret;
667 }
671 jvmtiError
672 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread, jobject *monitor_ptr) {
673 #ifdef ASSERT
674 uint32_t debug_bits = 0;
675 #endif
676 assert((SafepointSynchronize::is_at_safepoint() ||
677 is_thread_fully_suspended(java_thread, false, &debug_bits)),
678 "at safepoint or target thread is suspended");
679 oop obj = NULL;
680 ObjectMonitor *mon = java_thread->current_waiting_monitor();
681 if (mon == NULL) {
682 // thread is not doing an Object.wait() call
683 mon = java_thread->current_pending_monitor();
684 if (mon != NULL) {
685 // The thread is trying to enter() or raw_enter() an ObjectMonitor.
686 obj = (oop)mon->object();
687 // If obj == NULL, then ObjectMonitor is raw which doesn't count
688 // as contended for this API
689 }
690 // implied else: no contended ObjectMonitor
691 } else {
692 // thread is doing an Object.wait() call
693 obj = (oop)mon->object();
694 assert(obj != NULL, "Object.wait() should have an object");
695 }
697 if (obj == NULL) {
698 *monitor_ptr = NULL;
699 } else {
700 HandleMark hm;
701 Handle hobj(obj);
702 *monitor_ptr = jni_reference(calling_thread, hobj);
703 }
704 return JVMTI_ERROR_NONE;
705 }
708 jvmtiError
709 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
710 GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
711 jvmtiError err = JVMTI_ERROR_NONE;
712 #ifdef ASSERT
713 uint32_t debug_bits = 0;
714 #endif
715 assert((SafepointSynchronize::is_at_safepoint() ||
716 is_thread_fully_suspended(java_thread, false, &debug_bits)),
717 "at safepoint or target thread is suspended");
719 if (java_thread->has_last_Java_frame()) {
720 ResourceMark rm;
721 HandleMark hm;
722 RegisterMap reg_map(java_thread);
724 int depth = 0;
725 for (javaVFrame *jvf = java_thread->last_java_vframe(®_map); jvf != NULL;
726 jvf = jvf->java_sender()) {
727 if (depth++ < MaxJavaStackTraceDepth) { // check for stack too deep
728 // add locked objects for this frame into list
729 err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
730 if (err != JVMTI_ERROR_NONE) {
731 return err;
732 }
733 }
734 }
735 }
737 // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
738 JvmtiMonitorClosure jmc(java_thread, calling_thread, owned_monitors_list, this);
739 ObjectSynchronizer::monitors_iterate(&jmc);
740 err = jmc.error();
742 return err;
743 }
745 // Save JNI local handles for any objects that this frame owns.
746 jvmtiError
747 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
748 javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, int stack_depth) {
749 jvmtiError err = JVMTI_ERROR_NONE;
750 ResourceMark rm;
752 GrowableArray<MonitorInfo*>* mons = jvf->monitors();
753 if (mons->is_empty()) {
754 return err; // this javaVFrame holds no monitors
755 }
757 HandleMark hm;
758 oop wait_obj = NULL;
759 {
760 // save object of current wait() call (if any) for later comparison
761 ObjectMonitor *mon = java_thread->current_waiting_monitor();
762 if (mon != NULL) {
763 wait_obj = (oop)mon->object();
764 }
765 }
766 oop pending_obj = NULL;
767 {
768 // save object of current enter() call (if any) for later comparison
769 ObjectMonitor *mon = java_thread->current_pending_monitor();
770 if (mon != NULL) {
771 pending_obj = (oop)mon->object();
772 }
773 }
775 for (int i = 0; i < mons->length(); i++) {
776 MonitorInfo *mi = mons->at(i);
778 if (mi->owner_is_scalar_replaced()) continue;
780 oop obj = mi->owner();
781 if (obj == NULL) {
782 // this monitor doesn't have an owning object so skip it
783 continue;
784 }
786 if (wait_obj == obj) {
787 // the thread is waiting on this monitor so it isn't really owned
788 continue;
789 }
791 if (pending_obj == obj) {
792 // the thread is pending on this monitor so it isn't really owned
793 continue;
794 }
796 if (owned_monitors_list->length() > 0) {
797 // Our list has at least one object on it so we have to check
798 // for recursive object locking
799 bool found = false;
800 for (int j = 0; j < owned_monitors_list->length(); j++) {
801 jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
802 oop check = JNIHandles::resolve(jobj);
803 if (check == obj) {
804 found = true; // we found the object
805 break;
806 }
807 }
809 if (found) {
810 // already have this object so don't include it
811 continue;
812 }
813 }
815 // add the owning object to our list
816 jvmtiMonitorStackDepthInfo *jmsdi;
817 err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
818 if (err != JVMTI_ERROR_NONE) {
819 return err;
820 }
821 Handle hobj(obj);
822 jmsdi->monitor = jni_reference(calling_thread, hobj);
823 jmsdi->stack_depth = stack_depth;
824 owned_monitors_list->append(jmsdi);
825 }
827 return err;
828 }
830 jvmtiError
831 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
832 jint start_depth, jint max_count,
833 jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
834 #ifdef ASSERT
835 uint32_t debug_bits = 0;
836 #endif
837 assert((SafepointSynchronize::is_at_safepoint() ||
838 is_thread_fully_suspended(java_thread, false, &debug_bits)),
839 "at safepoint or target thread is suspended");
840 int count = 0;
841 if (java_thread->has_last_Java_frame()) {
842 RegisterMap reg_map(java_thread);
843 Thread* current_thread = Thread::current();
844 ResourceMark rm(current_thread);
845 javaVFrame *jvf = java_thread->last_java_vframe(®_map);
846 HandleMark hm(current_thread);
847 if (start_depth != 0) {
848 if (start_depth > 0) {
849 for (int j = 0; j < start_depth && jvf != NULL; j++) {
850 jvf = jvf->java_sender();
851 }
852 if (jvf == NULL) {
853 // start_depth is deeper than the stack depth
854 return JVMTI_ERROR_ILLEGAL_ARGUMENT;
855 }
856 } else { // start_depth < 0
857 // we are referencing the starting depth based on the oldest
858 // part of the stack.
859 // optimize to limit the number of times that java_sender() is called
860 javaVFrame *jvf_cursor = jvf;
861 javaVFrame *jvf_prev = NULL;
862 javaVFrame *jvf_prev_prev;
863 int j = 0;
864 while (jvf_cursor != NULL) {
865 jvf_prev_prev = jvf_prev;
866 jvf_prev = jvf_cursor;
867 for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
868 jvf_cursor = jvf_cursor->java_sender();
869 }
870 }
871 if (j == start_depth) {
872 // previous pointer is exactly where we want to start
873 jvf = jvf_prev;
874 } else {
875 // we need to back up further to get to the right place
876 if (jvf_prev_prev == NULL) {
877 // the -start_depth is greater than the stack depth
878 return JVMTI_ERROR_ILLEGAL_ARGUMENT;
879 }
880 // j now is the number of frames on the stack starting with
881 // jvf_prev, we start from jvf_prev_prev and move older on
882 // the stack that many, the result is -start_depth frames
883 // remaining.
884 jvf = jvf_prev_prev;
885 for (; j < 0; j++) {
886 jvf = jvf->java_sender();
887 }
888 }
889 }
890 }
891 for (; count < max_count && jvf != NULL; count++) {
892 frame_buffer[count].method = jvf->method()->jmethod_id();
893 frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
894 jvf = jvf->java_sender();
895 }
896 } else {
897 if (start_depth != 0) {
898 // no frames and there is a starting depth
899 return JVMTI_ERROR_ILLEGAL_ARGUMENT;
900 }
901 }
902 *count_ptr = count;
903 return JVMTI_ERROR_NONE;
904 }
906 jvmtiError
907 JvmtiEnvBase::get_frame_count(JvmtiThreadState *state, jint *count_ptr) {
908 assert((state != NULL),
909 "JavaThread should create JvmtiThreadState before calling this method");
910 *count_ptr = state->count_frames();
911 return JVMTI_ERROR_NONE;
912 }
914 jvmtiError
915 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
916 jmethodID* method_ptr, jlocation* location_ptr) {
917 #ifdef ASSERT
918 uint32_t debug_bits = 0;
919 #endif
920 assert((SafepointSynchronize::is_at_safepoint() ||
921 is_thread_fully_suspended(java_thread, false, &debug_bits)),
922 "at safepoint or target thread is suspended");
923 Thread* current_thread = Thread::current();
924 ResourceMark rm(current_thread);
926 vframe *vf = vframeFor(java_thread, depth);
927 if (vf == NULL) {
928 return JVMTI_ERROR_NO_MORE_FRAMES;
929 }
931 // vframeFor should return a java frame. If it doesn't
932 // it means we've got an internal error and we return the
933 // error in product mode. In debug mode we will instead
934 // attempt to cast the vframe to a javaVFrame and will
935 // cause an assertion/crash to allow further diagnosis.
936 #ifdef PRODUCT
937 if (!vf->is_java_frame()) {
938 return JVMTI_ERROR_INTERNAL;
939 }
940 #endif
942 HandleMark hm(current_thread);
943 javaVFrame *jvf = javaVFrame::cast(vf);
944 methodOop method = jvf->method();
945 if (method->is_native()) {
946 *location_ptr = -1;
947 } else {
948 *location_ptr = jvf->bci();
949 }
950 *method_ptr = method->jmethod_id();
952 return JVMTI_ERROR_NONE;
953 }
956 jvmtiError
957 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
958 HandleMark hm;
959 Handle hobj;
961 bool at_safepoint = SafepointSynchronize::is_at_safepoint();
963 // Check arguments
964 {
965 oop mirror = JNIHandles::resolve_external_guard(object);
966 NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
967 NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
969 hobj = Handle(mirror);
970 }
972 JavaThread *owning_thread = NULL;
973 ObjectMonitor *mon = NULL;
974 jvmtiMonitorUsage ret = {
975 NULL, 0, 0, NULL, 0, NULL
976 };
978 uint32_t debug_bits = 0;
979 // first derive the object's owner and entry_count (if any)
980 {
981 // Revoke any biases before querying the mark word
982 if (SafepointSynchronize::is_at_safepoint()) {
983 BiasedLocking::revoke_at_safepoint(hobj);
984 } else {
985 BiasedLocking::revoke_and_rebias(hobj, false, calling_thread);
986 }
988 address owner = NULL;
989 {
990 markOop mark = hobj()->mark();
992 if (!mark->has_monitor()) {
993 // this object has a lightweight monitor
995 if (mark->has_locker()) {
996 owner = (address)mark->locker(); // save the address of the Lock word
997 }
998 // implied else: no owner
999 } else {
1000 // this object has a heavyweight monitor
1001 mon = mark->monitor();
1003 // The owner field of a heavyweight monitor may be NULL for no
1004 // owner, a JavaThread * or it may still be the address of the
1005 // Lock word in a JavaThread's stack. A monitor can be inflated
1006 // by a non-owning JavaThread, but only the owning JavaThread
1007 // can change the owner field from the Lock word to the
1008 // JavaThread * and it may not have done that yet.
1009 owner = (address)mon->owner();
1010 }
1011 }
1013 if (owner != NULL) {
1014 // This monitor is owned so we have to find the owning JavaThread.
1015 // Since owning_thread_from_monitor_owner() grabs a lock, GC can
1016 // move our object at this point. However, our owner value is safe
1017 // since it is either the Lock word on a stack or a JavaThread *.
1018 owning_thread = Threads::owning_thread_from_monitor_owner(owner, !at_safepoint);
1019 assert(owning_thread != NULL, "sanity check");
1020 if (owning_thread != NULL) { // robustness
1021 // The monitor's owner either has to be the current thread, at safepoint
1022 // or it has to be suspended. Any of these conditions will prevent both
1023 // contending and waiting threads from modifying the state of
1024 // the monitor.
1025 if (!at_safepoint && !JvmtiEnv::is_thread_fully_suspended(owning_thread, true, &debug_bits)) {
1026 return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1027 }
1028 HandleMark hm;
1029 Handle th(owning_thread->threadObj());
1030 ret.owner = (jthread)jni_reference(calling_thread, th);
1031 }
1032 // implied else: no owner
1033 }
1035 if (owning_thread != NULL) { // monitor is owned
1036 if ((address)owning_thread == owner) {
1037 // the owner field is the JavaThread *
1038 assert(mon != NULL,
1039 "must have heavyweight monitor with JavaThread * owner");
1040 ret.entry_count = mon->recursions() + 1;
1041 } else {
1042 // The owner field is the Lock word on the JavaThread's stack
1043 // so the recursions field is not valid. We have to count the
1044 // number of recursive monitor entries the hard way. We pass
1045 // a handle to survive any GCs along the way.
1046 ResourceMark rm;
1047 ret.entry_count = count_locked_objects(owning_thread, hobj);
1048 }
1049 }
1050 // implied else: entry_count == 0
1051 }
1053 int nWant,nWait;
1054 if (mon != NULL) {
1055 // this object has a heavyweight monitor
1056 nWant = mon->contentions(); // # of threads contending for monitor
1057 nWait = mon->waiters(); // # of threads in Object.wait()
1058 ret.waiter_count = nWant + nWait;
1059 ret.notify_waiter_count = nWait;
1060 } else {
1061 // this object has a lightweight monitor
1062 ret.waiter_count = 0;
1063 ret.notify_waiter_count = 0;
1064 }
1066 // Allocate memory for heavyweight and lightweight monitor.
1067 jvmtiError err;
1068 err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
1069 if (err != JVMTI_ERROR_NONE) {
1070 return err;
1071 }
1072 err = allocate(ret.notify_waiter_count * sizeof(jthread *),
1073 (unsigned char**)&ret.notify_waiters);
1074 if (err != JVMTI_ERROR_NONE) {
1075 deallocate((unsigned char*)ret.waiters);
1076 return err;
1077 }
1079 // now derive the rest of the fields
1080 if (mon != NULL) {
1081 // this object has a heavyweight monitor
1083 // Number of waiters may actually be less than the waiter count.
1084 // So NULL out memory so that unused memory will be NULL.
1085 memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1086 memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1088 if (ret.waiter_count > 0) {
1089 // we have contending and/or waiting threads
1090 HandleMark hm;
1091 if (nWant > 0) {
1092 // we have contending threads
1093 ResourceMark rm;
1094 // get_pending_threads returns only java thread so we do not need to
1095 // check for non java threads.
1096 GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(
1097 nWant, (address)mon, !at_safepoint);
1098 if (wantList->length() < nWant) {
1099 // robustness: the pending list has gotten smaller
1100 nWant = wantList->length();
1101 }
1102 for (int i = 0; i < nWant; i++) {
1103 JavaThread *pending_thread = wantList->at(i);
1104 // If the monitor has no owner, then a non-suspended contending
1105 // thread could potentially change the state of the monitor by
1106 // entering it. The JVM/TI spec doesn't allow this.
1107 if (owning_thread == NULL && !at_safepoint &
1108 !JvmtiEnv::is_thread_fully_suspended(pending_thread, true, &debug_bits)) {
1109 if (ret.owner != NULL) {
1110 destroy_jni_reference(calling_thread, ret.owner);
1111 }
1112 for (int j = 0; j < i; j++) {
1113 destroy_jni_reference(calling_thread, ret.waiters[j]);
1114 }
1115 deallocate((unsigned char*)ret.waiters);
1116 deallocate((unsigned char*)ret.notify_waiters);
1117 return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1118 }
1119 Handle th(pending_thread->threadObj());
1120 ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1121 }
1122 }
1123 if (nWait > 0) {
1124 // we have threads in Object.wait()
1125 int offset = nWant; // add after any contending threads
1126 ObjectWaiter *waiter = mon->first_waiter();
1127 for (int i = 0, j = 0; i < nWait; i++) {
1128 if (waiter == NULL) {
1129 // robustness: the waiting list has gotten smaller
1130 nWait = j;
1131 break;
1132 }
1133 Thread *t = mon->thread_of_waiter(waiter);
1134 if (t != NULL && t->is_Java_thread()) {
1135 JavaThread *wjava_thread = (JavaThread *)t;
1136 // If the thread was found on the ObjectWaiter list, then
1137 // it has not been notified. This thread can't change the
1138 // state of the monitor so it doesn't need to be suspended.
1139 Handle th(wjava_thread->threadObj());
1140 ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1141 ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1142 }
1143 waiter = mon->next_waiter(waiter);
1144 }
1145 }
1146 }
1148 // Adjust count. nWant and nWait count values may be less than original.
1149 ret.waiter_count = nWant + nWait;
1150 ret.notify_waiter_count = nWait;
1151 } else {
1152 // this object has a lightweight monitor and we have nothing more
1153 // to do here because the defaults are just fine.
1154 }
1156 // we don't update return parameter unless everything worked
1157 *info_ptr = ret;
1159 return JVMTI_ERROR_NONE;
1160 }
1162 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1163 _env = env;
1164 _allocations = new (ResourceObj::C_HEAP) GrowableArray<unsigned char*>(20, true);
1165 _failed = false;
1166 }
1167 ResourceTracker::~ResourceTracker() {
1168 if (_failed) {
1169 for (int i=0; i<_allocations->length(); i++) {
1170 _env->deallocate(_allocations->at(i));
1171 }
1172 }
1173 delete _allocations;
1174 }
1176 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1177 unsigned char *ptr;
1178 jvmtiError err = _env->allocate(size, &ptr);
1179 if (err == JVMTI_ERROR_NONE) {
1180 _allocations->append(ptr);
1181 *mem_ptr = ptr;
1182 } else {
1183 *mem_ptr = NULL;
1184 _failed = true;
1185 }
1186 return err;
1187 }
1189 unsigned char* ResourceTracker::allocate(jlong size) {
1190 unsigned char* ptr;
1191 allocate(size, &ptr);
1192 return ptr;
1193 }
1195 char* ResourceTracker::strdup(const char* str) {
1196 char *dup_str = (char*)allocate(strlen(str)+1);
1197 if (dup_str != NULL) {
1198 strcpy(dup_str, str);
1199 }
1200 return dup_str;
1201 }
1203 struct StackInfoNode {
1204 struct StackInfoNode *next;
1205 jvmtiStackInfo info;
1206 };
1208 // Create a jvmtiStackInfo inside a linked list node and create a
1209 // buffer for the frame information, both allocated as resource objects.
1210 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1211 // Note that either or both of thr and thread_oop
1212 // may be null if the thread is new or has exited.
1213 void
1214 VM_GetMultipleStackTraces::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1215 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1217 jint state = 0;
1218 struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
1219 jvmtiStackInfo *infop = &(node->info);
1220 node->next = head();
1221 set_head(node);
1222 infop->frame_count = 0;
1223 infop->thread = jt;
1225 if (thread_oop != NULL) {
1226 // get most state bits
1227 state = (jint)java_lang_Thread::get_thread_status(thread_oop);
1228 }
1230 if (thr != NULL) { // add more state bits if there is a JavaThead to query
1231 // same as is_being_ext_suspended() but without locking
1232 if (thr->is_ext_suspended() || thr->is_external_suspend()) {
1233 state |= JVMTI_THREAD_STATE_SUSPENDED;
1234 }
1235 JavaThreadState jts = thr->thread_state();
1236 if (jts == _thread_in_native) {
1237 state |= JVMTI_THREAD_STATE_IN_NATIVE;
1238 }
1239 OSThread* osThread = thr->osthread();
1240 if (osThread != NULL && osThread->interrupted()) {
1241 state |= JVMTI_THREAD_STATE_INTERRUPTED;
1242 }
1243 }
1244 infop->state = state;
1246 if (thr != NULL || (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1247 infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1248 env()->get_stack_trace(thr, 0, max_frame_count(),
1249 infop->frame_buffer, &(infop->frame_count));
1250 } else {
1251 infop->frame_buffer = NULL;
1252 infop->frame_count = 0;
1253 }
1254 _frame_count_total += infop->frame_count;
1255 }
1257 // Based on the stack information in the linked list, allocate memory
1258 // block to return and fill it from the info in the linked list.
1259 void
1260 VM_GetMultipleStackTraces::allocate_and_fill_stacks(jint thread_count) {
1261 // do I need to worry about alignment issues?
1262 jlong alloc_size = thread_count * sizeof(jvmtiStackInfo)
1263 + _frame_count_total * sizeof(jvmtiFrameInfo);
1264 env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1266 // pointers to move through the newly allocated space as it is filled in
1267 jvmtiStackInfo *si = _stack_info + thread_count; // bottom of stack info
1268 jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si; // is the top of frame info
1270 // copy information in resource area into allocated buffer
1271 // insert stack info backwards since linked list is backwards
1272 // insert frame info forwards
1273 // walk the StackInfoNodes
1274 for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {
1275 jint frame_count = sin->info.frame_count;
1276 size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
1277 --si;
1278 memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
1279 if (frames_size == 0) {
1280 si->frame_buffer = NULL;
1281 } else {
1282 memcpy(fi, sin->info.frame_buffer, frames_size);
1283 si->frame_buffer = fi; // point to the new allocated copy of the frames
1284 fi += frame_count;
1285 }
1286 }
1287 assert(si == _stack_info, "the last copied stack info must be the first record");
1288 assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1289 "the last copied frame info must be the last record");
1290 }
1293 void
1294 VM_GetThreadListStackTraces::doit() {
1295 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1297 ResourceMark rm;
1298 for (int i = 0; i < _thread_count; ++i) {
1299 jthread jt = _thread_list[i];
1300 oop thread_oop = JNIHandles::resolve_external_guard(jt);
1301 if (thread_oop == NULL || !thread_oop->is_a(SystemDictionary::Thread_klass())) {
1302 set_result(JVMTI_ERROR_INVALID_THREAD);
1303 return;
1304 }
1305 fill_frames(jt, java_lang_Thread::thread(thread_oop), thread_oop);
1306 }
1307 allocate_and_fill_stacks(_thread_count);
1308 }
1310 void
1311 VM_GetAllStackTraces::doit() {
1312 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1314 ResourceMark rm;
1315 _final_thread_count = 0;
1316 for (JavaThread *jt = Threads::first(); jt != NULL; jt = jt->next()) {
1317 oop thread_oop = jt->threadObj();
1318 if (thread_oop != NULL &&
1319 !jt->is_exiting() &&
1320 java_lang_Thread::is_alive(thread_oop) &&
1321 !jt->is_hidden_from_external_view()) {
1322 ++_final_thread_count;
1323 // Handle block of the calling thread is used to create local refs.
1324 fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
1325 jt, thread_oop);
1326 }
1327 }
1328 allocate_and_fill_stacks(_final_thread_count);
1329 }
1331 // Verifies that the top frame is a java frame in an expected state.
1332 // Deoptimizes frame if needed.
1333 // Checks that the frame method signature matches the return type (tos).
1334 // HandleMark must be defined in the caller only.
1335 // It is to keep a ret_ob_h handle alive after return to the caller.
1336 jvmtiError
1337 JvmtiEnvBase::check_top_frame(JavaThread* current_thread, JavaThread* java_thread,
1338 jvalue value, TosState tos, Handle* ret_ob_h) {
1339 ResourceMark rm(current_thread);
1341 vframe *vf = vframeFor(java_thread, 0);
1342 NULL_CHECK(vf, JVMTI_ERROR_NO_MORE_FRAMES);
1344 javaVFrame *jvf = (javaVFrame*) vf;
1345 if (!vf->is_java_frame() || jvf->method()->is_native()) {
1346 return JVMTI_ERROR_OPAQUE_FRAME;
1347 }
1349 // If the frame is a compiled one, need to deoptimize it.
1350 if (vf->is_compiled_frame()) {
1351 if (!vf->fr().can_be_deoptimized()) {
1352 return JVMTI_ERROR_OPAQUE_FRAME;
1353 }
1354 Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());
1355 }
1357 // Get information about method return type
1358 symbolHandle signature(current_thread, jvf->method()->signature());
1360 ResultTypeFinder rtf(signature);
1361 TosState fr_tos = as_TosState(rtf.type());
1362 if (fr_tos != tos) {
1363 if (tos != itos || (fr_tos != btos && fr_tos != ctos && fr_tos != stos)) {
1364 return JVMTI_ERROR_TYPE_MISMATCH;
1365 }
1366 }
1368 // Check that the jobject class matches the return type signature.
1369 jobject jobj = value.l;
1370 if (tos == atos && jobj != NULL) { // NULL reference is allowed
1371 Handle ob_h = Handle(current_thread, JNIHandles::resolve_external_guard(jobj));
1372 NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
1373 KlassHandle ob_kh = KlassHandle(current_thread, ob_h()->klass());
1374 NULL_CHECK(ob_kh, JVMTI_ERROR_INVALID_OBJECT);
1376 // Method return type signature.
1377 char* ty_sign = 1 + strchr(signature->as_C_string(), ')');
1379 if (!VM_GetOrSetLocal::is_assignable(ty_sign, Klass::cast(ob_kh()), current_thread)) {
1380 return JVMTI_ERROR_TYPE_MISMATCH;
1381 }
1382 *ret_ob_h = ob_h;
1383 }
1384 return JVMTI_ERROR_NONE;
1385 } /* end check_top_frame */
1388 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
1389 // Main difference is on the last stage in the interpreter.
1390 // The PopFrame stops method execution to continue execution
1391 // from the same method call instruction.
1392 // The ForceEarlyReturn forces return from method so the execution
1393 // continues at the bytecode following the method call.
1395 // Threads_lock NOT held, java_thread not protected by lock
1396 // java_thread - pre-checked
1398 jvmtiError
1399 JvmtiEnvBase::force_early_return(JavaThread* java_thread, jvalue value, TosState tos) {
1400 JavaThread* current_thread = JavaThread::current();
1401 HandleMark hm(current_thread);
1402 uint32_t debug_bits = 0;
1404 // retrieve or create the state
1405 JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1406 if (state == NULL) {
1407 return JVMTI_ERROR_THREAD_NOT_ALIVE;
1408 }
1410 // Check if java_thread is fully suspended
1411 if (!is_thread_fully_suspended(java_thread,
1412 true /* wait for suspend completion */,
1413 &debug_bits)) {
1414 return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1415 }
1417 // Check to see if a ForceEarlyReturn was already in progress
1418 if (state->is_earlyret_pending()) {
1419 // Probably possible for JVMTI clients to trigger this, but the
1420 // JPDA backend shouldn't allow this to happen
1421 return JVMTI_ERROR_INTERNAL;
1422 }
1423 {
1424 // The same as for PopFrame. Workaround bug:
1425 // 4812902: popFrame hangs if the method is waiting at a synchronize
1426 // Catch this condition and return an error to avoid hanging.
1427 // Now JVMTI spec allows an implementation to bail out with an opaque
1428 // frame error.
1429 OSThread* osThread = java_thread->osthread();
1430 if (osThread->get_state() == MONITOR_WAIT) {
1431 return JVMTI_ERROR_OPAQUE_FRAME;
1432 }
1433 }
1434 Handle ret_ob_h = Handle();
1435 jvmtiError err = check_top_frame(current_thread, java_thread, value, tos, &ret_ob_h);
1436 if (err != JVMTI_ERROR_NONE) {
1437 return err;
1438 }
1439 assert(tos != atos || value.l == NULL || ret_ob_h() != NULL,
1440 "return object oop must not be NULL if jobject is not NULL");
1442 // Update the thread state to reflect that the top frame must be
1443 // forced to return.
1444 // The current frame will be returned later when the suspended
1445 // thread is resumed and right before returning from VM to Java.
1446 // (see call_VM_base() in assembler_<cpu>.cpp).
1448 state->set_earlyret_pending();
1449 state->set_earlyret_oop(ret_ob_h());
1450 state->set_earlyret_value(value, tos);
1452 // Set pending step flag for this early return.
1453 // It is cleared when next step event is posted.
1454 state->set_pending_step_for_earlyret();
1456 return JVMTI_ERROR_NONE;
1457 } /* end force_early_return */
1459 void
1460 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
1461 if ( _error != JVMTI_ERROR_NONE) {
1462 // Error occurred in previous iteration so no need to add
1463 // to the list.
1464 return;
1465 }
1466 if (mon->owner() == _java_thread ) {
1467 // Filter out on stack monitors collected during stack walk.
1468 oop obj = (oop)mon->object();
1469 bool found = false;
1470 for (int j = 0; j < _owned_monitors_list->length(); j++) {
1471 jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
1472 oop check = JNIHandles::resolve(jobj);
1473 if (check == obj) {
1474 // On stack monitor already collected during the stack walk.
1475 found = true;
1476 break;
1477 }
1478 }
1479 if (found == false) {
1480 // This is off stack monitor (e.g. acquired via jni MonitorEnter).
1481 jvmtiError err;
1482 jvmtiMonitorStackDepthInfo *jmsdi;
1483 err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1484 if (err != JVMTI_ERROR_NONE) {
1485 _error = err;
1486 return;
1487 }
1488 Handle hobj(obj);
1489 jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
1490 // stack depth is unknown for this monitor.
1491 jmsdi->stack_depth = -1;
1492 _owned_monitors_list->append(jmsdi);
1493 }
1494 }
1495 }
1497 #endif // !JVMTI_KERNEL