Thu, 23 Jun 2011 17:14:06 -0700
7056328: JSR 292 invocation sometimes fails in adapters for types not on boot class path
Reviewed-by: never
1 /*
2 * Copyright (c) 2003, 2011, 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 found = id->find_local_field(fd);
620 } else {
621 // Non-static field. The fieldID is really the offset of the field within the object.
622 int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);
623 found = instanceKlass::cast(k)->find_field_from_offset(offset, false, fd);
624 }
625 return found;
626 }
628 //
629 // Object Monitor Information
630 //
632 //
633 // Count the number of objects for a lightweight monitor. The hobj
634 // parameter is object that owns the monitor so this routine will
635 // count the number of times the same object was locked by frames
636 // in java_thread.
637 //
638 jint
639 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
640 jint ret = 0;
641 if (!java_thread->has_last_Java_frame()) {
642 return ret; // no Java frames so no monitors
643 }
645 ResourceMark rm;
646 HandleMark hm;
647 RegisterMap reg_map(java_thread);
649 for(javaVFrame *jvf=java_thread->last_java_vframe(®_map); jvf != NULL;
650 jvf = jvf->java_sender()) {
651 GrowableArray<MonitorInfo*>* mons = jvf->monitors();
652 if (!mons->is_empty()) {
653 for (int i = 0; i < mons->length(); i++) {
654 MonitorInfo *mi = mons->at(i);
655 if (mi->owner_is_scalar_replaced()) continue;
657 // see if owner of the monitor is our object
658 if (mi->owner() != NULL && mi->owner() == hobj()) {
659 ret++;
660 }
661 }
662 }
663 }
664 return ret;
665 }
669 jvmtiError
670 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread, jobject *monitor_ptr) {
671 #ifdef ASSERT
672 uint32_t debug_bits = 0;
673 #endif
674 assert((SafepointSynchronize::is_at_safepoint() ||
675 is_thread_fully_suspended(java_thread, false, &debug_bits)),
676 "at safepoint or target thread is suspended");
677 oop obj = NULL;
678 ObjectMonitor *mon = java_thread->current_waiting_monitor();
679 if (mon == NULL) {
680 // thread is not doing an Object.wait() call
681 mon = java_thread->current_pending_monitor();
682 if (mon != NULL) {
683 // The thread is trying to enter() or raw_enter() an ObjectMonitor.
684 obj = (oop)mon->object();
685 // If obj == NULL, then ObjectMonitor is raw which doesn't count
686 // as contended for this API
687 }
688 // implied else: no contended ObjectMonitor
689 } else {
690 // thread is doing an Object.wait() call
691 obj = (oop)mon->object();
692 assert(obj != NULL, "Object.wait() should have an object");
693 }
695 if (obj == NULL) {
696 *monitor_ptr = NULL;
697 } else {
698 HandleMark hm;
699 Handle hobj(obj);
700 *monitor_ptr = jni_reference(calling_thread, hobj);
701 }
702 return JVMTI_ERROR_NONE;
703 }
706 jvmtiError
707 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
708 GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
709 jvmtiError err = JVMTI_ERROR_NONE;
710 #ifdef ASSERT
711 uint32_t debug_bits = 0;
712 #endif
713 assert((SafepointSynchronize::is_at_safepoint() ||
714 is_thread_fully_suspended(java_thread, false, &debug_bits)),
715 "at safepoint or target thread is suspended");
717 if (java_thread->has_last_Java_frame()) {
718 ResourceMark rm;
719 HandleMark hm;
720 RegisterMap reg_map(java_thread);
722 int depth = 0;
723 for (javaVFrame *jvf = java_thread->last_java_vframe(®_map); jvf != NULL;
724 jvf = jvf->java_sender()) {
725 if (depth++ < MaxJavaStackTraceDepth) { // check for stack too deep
726 // add locked objects for this frame into list
727 err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
728 if (err != JVMTI_ERROR_NONE) {
729 return err;
730 }
731 }
732 }
733 }
735 // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
736 JvmtiMonitorClosure jmc(java_thread, calling_thread, owned_monitors_list, this);
737 ObjectSynchronizer::monitors_iterate(&jmc);
738 err = jmc.error();
740 return err;
741 }
743 // Save JNI local handles for any objects that this frame owns.
744 jvmtiError
745 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
746 javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, int stack_depth) {
747 jvmtiError err = JVMTI_ERROR_NONE;
748 ResourceMark rm;
750 GrowableArray<MonitorInfo*>* mons = jvf->monitors();
751 if (mons->is_empty()) {
752 return err; // this javaVFrame holds no monitors
753 }
755 HandleMark hm;
756 oop wait_obj = NULL;
757 {
758 // save object of current wait() call (if any) for later comparison
759 ObjectMonitor *mon = java_thread->current_waiting_monitor();
760 if (mon != NULL) {
761 wait_obj = (oop)mon->object();
762 }
763 }
764 oop pending_obj = NULL;
765 {
766 // save object of current enter() call (if any) for later comparison
767 ObjectMonitor *mon = java_thread->current_pending_monitor();
768 if (mon != NULL) {
769 pending_obj = (oop)mon->object();
770 }
771 }
773 for (int i = 0; i < mons->length(); i++) {
774 MonitorInfo *mi = mons->at(i);
776 if (mi->owner_is_scalar_replaced()) continue;
778 oop obj = mi->owner();
779 if (obj == NULL) {
780 // this monitor doesn't have an owning object so skip it
781 continue;
782 }
784 if (wait_obj == obj) {
785 // the thread is waiting on this monitor so it isn't really owned
786 continue;
787 }
789 if (pending_obj == obj) {
790 // the thread is pending on this monitor so it isn't really owned
791 continue;
792 }
794 if (owned_monitors_list->length() > 0) {
795 // Our list has at least one object on it so we have to check
796 // for recursive object locking
797 bool found = false;
798 for (int j = 0; j < owned_monitors_list->length(); j++) {
799 jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
800 oop check = JNIHandles::resolve(jobj);
801 if (check == obj) {
802 found = true; // we found the object
803 break;
804 }
805 }
807 if (found) {
808 // already have this object so don't include it
809 continue;
810 }
811 }
813 // add the owning object to our list
814 jvmtiMonitorStackDepthInfo *jmsdi;
815 err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
816 if (err != JVMTI_ERROR_NONE) {
817 return err;
818 }
819 Handle hobj(obj);
820 jmsdi->monitor = jni_reference(calling_thread, hobj);
821 jmsdi->stack_depth = stack_depth;
822 owned_monitors_list->append(jmsdi);
823 }
825 return err;
826 }
828 jvmtiError
829 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
830 jint start_depth, jint max_count,
831 jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
832 #ifdef ASSERT
833 uint32_t debug_bits = 0;
834 #endif
835 assert((SafepointSynchronize::is_at_safepoint() ||
836 is_thread_fully_suspended(java_thread, false, &debug_bits)),
837 "at safepoint or target thread is suspended");
838 int count = 0;
839 if (java_thread->has_last_Java_frame()) {
840 RegisterMap reg_map(java_thread);
841 Thread* current_thread = Thread::current();
842 ResourceMark rm(current_thread);
843 javaVFrame *jvf = java_thread->last_java_vframe(®_map);
844 HandleMark hm(current_thread);
845 if (start_depth != 0) {
846 if (start_depth > 0) {
847 for (int j = 0; j < start_depth && jvf != NULL; j++) {
848 jvf = jvf->java_sender();
849 }
850 if (jvf == NULL) {
851 // start_depth is deeper than the stack depth
852 return JVMTI_ERROR_ILLEGAL_ARGUMENT;
853 }
854 } else { // start_depth < 0
855 // we are referencing the starting depth based on the oldest
856 // part of the stack.
857 // optimize to limit the number of times that java_sender() is called
858 javaVFrame *jvf_cursor = jvf;
859 javaVFrame *jvf_prev = NULL;
860 javaVFrame *jvf_prev_prev;
861 int j = 0;
862 while (jvf_cursor != NULL) {
863 jvf_prev_prev = jvf_prev;
864 jvf_prev = jvf_cursor;
865 for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
866 jvf_cursor = jvf_cursor->java_sender();
867 }
868 }
869 if (j == start_depth) {
870 // previous pointer is exactly where we want to start
871 jvf = jvf_prev;
872 } else {
873 // we need to back up further to get to the right place
874 if (jvf_prev_prev == NULL) {
875 // the -start_depth is greater than the stack depth
876 return JVMTI_ERROR_ILLEGAL_ARGUMENT;
877 }
878 // j now is the number of frames on the stack starting with
879 // jvf_prev, we start from jvf_prev_prev and move older on
880 // the stack that many, the result is -start_depth frames
881 // remaining.
882 jvf = jvf_prev_prev;
883 for (; j < 0; j++) {
884 jvf = jvf->java_sender();
885 }
886 }
887 }
888 }
889 for (; count < max_count && jvf != NULL; count++) {
890 frame_buffer[count].method = jvf->method()->jmethod_id();
891 frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
892 jvf = jvf->java_sender();
893 }
894 } else {
895 if (start_depth != 0) {
896 // no frames and there is a starting depth
897 return JVMTI_ERROR_ILLEGAL_ARGUMENT;
898 }
899 }
900 *count_ptr = count;
901 return JVMTI_ERROR_NONE;
902 }
904 jvmtiError
905 JvmtiEnvBase::get_frame_count(JvmtiThreadState *state, jint *count_ptr) {
906 assert((state != NULL),
907 "JavaThread should create JvmtiThreadState before calling this method");
908 *count_ptr = state->count_frames();
909 return JVMTI_ERROR_NONE;
910 }
912 jvmtiError
913 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
914 jmethodID* method_ptr, jlocation* location_ptr) {
915 #ifdef ASSERT
916 uint32_t debug_bits = 0;
917 #endif
918 assert((SafepointSynchronize::is_at_safepoint() ||
919 is_thread_fully_suspended(java_thread, false, &debug_bits)),
920 "at safepoint or target thread is suspended");
921 Thread* current_thread = Thread::current();
922 ResourceMark rm(current_thread);
924 vframe *vf = vframeFor(java_thread, depth);
925 if (vf == NULL) {
926 return JVMTI_ERROR_NO_MORE_FRAMES;
927 }
929 // vframeFor should return a java frame. If it doesn't
930 // it means we've got an internal error and we return the
931 // error in product mode. In debug mode we will instead
932 // attempt to cast the vframe to a javaVFrame and will
933 // cause an assertion/crash to allow further diagnosis.
934 #ifdef PRODUCT
935 if (!vf->is_java_frame()) {
936 return JVMTI_ERROR_INTERNAL;
937 }
938 #endif
940 HandleMark hm(current_thread);
941 javaVFrame *jvf = javaVFrame::cast(vf);
942 methodOop method = jvf->method();
943 if (method->is_native()) {
944 *location_ptr = -1;
945 } else {
946 *location_ptr = jvf->bci();
947 }
948 *method_ptr = method->jmethod_id();
950 return JVMTI_ERROR_NONE;
951 }
954 jvmtiError
955 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
956 HandleMark hm;
957 Handle hobj;
959 bool at_safepoint = SafepointSynchronize::is_at_safepoint();
961 // Check arguments
962 {
963 oop mirror = JNIHandles::resolve_external_guard(object);
964 NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
965 NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
967 hobj = Handle(mirror);
968 }
970 JavaThread *owning_thread = NULL;
971 ObjectMonitor *mon = NULL;
972 jvmtiMonitorUsage ret = {
973 NULL, 0, 0, NULL, 0, NULL
974 };
976 uint32_t debug_bits = 0;
977 // first derive the object's owner and entry_count (if any)
978 {
979 // Revoke any biases before querying the mark word
980 if (SafepointSynchronize::is_at_safepoint()) {
981 BiasedLocking::revoke_at_safepoint(hobj);
982 } else {
983 BiasedLocking::revoke_and_rebias(hobj, false, calling_thread);
984 }
986 address owner = NULL;
987 {
988 markOop mark = hobj()->mark();
990 if (!mark->has_monitor()) {
991 // this object has a lightweight monitor
993 if (mark->has_locker()) {
994 owner = (address)mark->locker(); // save the address of the Lock word
995 }
996 // implied else: no owner
997 } else {
998 // this object has a heavyweight monitor
999 mon = mark->monitor();
1001 // The owner field of a heavyweight monitor may be NULL for no
1002 // owner, a JavaThread * or it may still be the address of the
1003 // Lock word in a JavaThread's stack. A monitor can be inflated
1004 // by a non-owning JavaThread, but only the owning JavaThread
1005 // can change the owner field from the Lock word to the
1006 // JavaThread * and it may not have done that yet.
1007 owner = (address)mon->owner();
1008 }
1009 }
1011 if (owner != NULL) {
1012 // This monitor is owned so we have to find the owning JavaThread.
1013 // Since owning_thread_from_monitor_owner() grabs a lock, GC can
1014 // move our object at this point. However, our owner value is safe
1015 // since it is either the Lock word on a stack or a JavaThread *.
1016 owning_thread = Threads::owning_thread_from_monitor_owner(owner, !at_safepoint);
1017 assert(owning_thread != NULL, "sanity check");
1018 if (owning_thread != NULL) { // robustness
1019 // The monitor's owner either has to be the current thread, at safepoint
1020 // or it has to be suspended. Any of these conditions will prevent both
1021 // contending and waiting threads from modifying the state of
1022 // the monitor.
1023 if (!at_safepoint && !JvmtiEnv::is_thread_fully_suspended(owning_thread, true, &debug_bits)) {
1024 return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1025 }
1026 HandleMark hm;
1027 Handle th(owning_thread->threadObj());
1028 ret.owner = (jthread)jni_reference(calling_thread, th);
1029 }
1030 // implied else: no owner
1031 }
1033 if (owning_thread != NULL) { // monitor is owned
1034 if ((address)owning_thread == owner) {
1035 // the owner field is the JavaThread *
1036 assert(mon != NULL,
1037 "must have heavyweight monitor with JavaThread * owner");
1038 ret.entry_count = mon->recursions() + 1;
1039 } else {
1040 // The owner field is the Lock word on the JavaThread's stack
1041 // so the recursions field is not valid. We have to count the
1042 // number of recursive monitor entries the hard way. We pass
1043 // a handle to survive any GCs along the way.
1044 ResourceMark rm;
1045 ret.entry_count = count_locked_objects(owning_thread, hobj);
1046 }
1047 }
1048 // implied else: entry_count == 0
1049 }
1051 int nWant,nWait;
1052 if (mon != NULL) {
1053 // this object has a heavyweight monitor
1054 nWant = mon->contentions(); // # of threads contending for monitor
1055 nWait = mon->waiters(); // # of threads in Object.wait()
1056 ret.waiter_count = nWant + nWait;
1057 ret.notify_waiter_count = nWait;
1058 } else {
1059 // this object has a lightweight monitor
1060 ret.waiter_count = 0;
1061 ret.notify_waiter_count = 0;
1062 }
1064 // Allocate memory for heavyweight and lightweight monitor.
1065 jvmtiError err;
1066 err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
1067 if (err != JVMTI_ERROR_NONE) {
1068 return err;
1069 }
1070 err = allocate(ret.notify_waiter_count * sizeof(jthread *),
1071 (unsigned char**)&ret.notify_waiters);
1072 if (err != JVMTI_ERROR_NONE) {
1073 deallocate((unsigned char*)ret.waiters);
1074 return err;
1075 }
1077 // now derive the rest of the fields
1078 if (mon != NULL) {
1079 // this object has a heavyweight monitor
1081 // Number of waiters may actually be less than the waiter count.
1082 // So NULL out memory so that unused memory will be NULL.
1083 memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1084 memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1086 if (ret.waiter_count > 0) {
1087 // we have contending and/or waiting threads
1088 HandleMark hm;
1089 if (nWant > 0) {
1090 // we have contending threads
1091 ResourceMark rm;
1092 // get_pending_threads returns only java thread so we do not need to
1093 // check for non java threads.
1094 GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(
1095 nWant, (address)mon, !at_safepoint);
1096 if (wantList->length() < nWant) {
1097 // robustness: the pending list has gotten smaller
1098 nWant = wantList->length();
1099 }
1100 for (int i = 0; i < nWant; i++) {
1101 JavaThread *pending_thread = wantList->at(i);
1102 // If the monitor has no owner, then a non-suspended contending
1103 // thread could potentially change the state of the monitor by
1104 // entering it. The JVM/TI spec doesn't allow this.
1105 if (owning_thread == NULL && !at_safepoint &
1106 !JvmtiEnv::is_thread_fully_suspended(pending_thread, true, &debug_bits)) {
1107 if (ret.owner != NULL) {
1108 destroy_jni_reference(calling_thread, ret.owner);
1109 }
1110 for (int j = 0; j < i; j++) {
1111 destroy_jni_reference(calling_thread, ret.waiters[j]);
1112 }
1113 deallocate((unsigned char*)ret.waiters);
1114 deallocate((unsigned char*)ret.notify_waiters);
1115 return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1116 }
1117 Handle th(pending_thread->threadObj());
1118 ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1119 }
1120 }
1121 if (nWait > 0) {
1122 // we have threads in Object.wait()
1123 int offset = nWant; // add after any contending threads
1124 ObjectWaiter *waiter = mon->first_waiter();
1125 for (int i = 0, j = 0; i < nWait; i++) {
1126 if (waiter == NULL) {
1127 // robustness: the waiting list has gotten smaller
1128 nWait = j;
1129 break;
1130 }
1131 Thread *t = mon->thread_of_waiter(waiter);
1132 if (t != NULL && t->is_Java_thread()) {
1133 JavaThread *wjava_thread = (JavaThread *)t;
1134 // If the thread was found on the ObjectWaiter list, then
1135 // it has not been notified. This thread can't change the
1136 // state of the monitor so it doesn't need to be suspended.
1137 Handle th(wjava_thread->threadObj());
1138 ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1139 ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1140 }
1141 waiter = mon->next_waiter(waiter);
1142 }
1143 }
1144 }
1146 // Adjust count. nWant and nWait count values may be less than original.
1147 ret.waiter_count = nWant + nWait;
1148 ret.notify_waiter_count = nWait;
1149 } else {
1150 // this object has a lightweight monitor and we have nothing more
1151 // to do here because the defaults are just fine.
1152 }
1154 // we don't update return parameter unless everything worked
1155 *info_ptr = ret;
1157 return JVMTI_ERROR_NONE;
1158 }
1160 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1161 _env = env;
1162 _allocations = new (ResourceObj::C_HEAP) GrowableArray<unsigned char*>(20, true);
1163 _failed = false;
1164 }
1165 ResourceTracker::~ResourceTracker() {
1166 if (_failed) {
1167 for (int i=0; i<_allocations->length(); i++) {
1168 _env->deallocate(_allocations->at(i));
1169 }
1170 }
1171 delete _allocations;
1172 }
1174 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1175 unsigned char *ptr;
1176 jvmtiError err = _env->allocate(size, &ptr);
1177 if (err == JVMTI_ERROR_NONE) {
1178 _allocations->append(ptr);
1179 *mem_ptr = ptr;
1180 } else {
1181 *mem_ptr = NULL;
1182 _failed = true;
1183 }
1184 return err;
1185 }
1187 unsigned char* ResourceTracker::allocate(jlong size) {
1188 unsigned char* ptr;
1189 allocate(size, &ptr);
1190 return ptr;
1191 }
1193 char* ResourceTracker::strdup(const char* str) {
1194 char *dup_str = (char*)allocate(strlen(str)+1);
1195 if (dup_str != NULL) {
1196 strcpy(dup_str, str);
1197 }
1198 return dup_str;
1199 }
1201 struct StackInfoNode {
1202 struct StackInfoNode *next;
1203 jvmtiStackInfo info;
1204 };
1206 // Create a jvmtiStackInfo inside a linked list node and create a
1207 // buffer for the frame information, both allocated as resource objects.
1208 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1209 // Note that either or both of thr and thread_oop
1210 // may be null if the thread is new or has exited.
1211 void
1212 VM_GetMultipleStackTraces::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1213 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1215 jint state = 0;
1216 struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
1217 jvmtiStackInfo *infop = &(node->info);
1218 node->next = head();
1219 set_head(node);
1220 infop->frame_count = 0;
1221 infop->thread = jt;
1223 if (thread_oop != NULL) {
1224 // get most state bits
1225 state = (jint)java_lang_Thread::get_thread_status(thread_oop);
1226 }
1228 if (thr != NULL) { // add more state bits if there is a JavaThead to query
1229 // same as is_being_ext_suspended() but without locking
1230 if (thr->is_ext_suspended() || thr->is_external_suspend()) {
1231 state |= JVMTI_THREAD_STATE_SUSPENDED;
1232 }
1233 JavaThreadState jts = thr->thread_state();
1234 if (jts == _thread_in_native) {
1235 state |= JVMTI_THREAD_STATE_IN_NATIVE;
1236 }
1237 OSThread* osThread = thr->osthread();
1238 if (osThread != NULL && osThread->interrupted()) {
1239 state |= JVMTI_THREAD_STATE_INTERRUPTED;
1240 }
1241 }
1242 infop->state = state;
1244 if (thr != NULL || (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1245 infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1246 env()->get_stack_trace(thr, 0, max_frame_count(),
1247 infop->frame_buffer, &(infop->frame_count));
1248 } else {
1249 infop->frame_buffer = NULL;
1250 infop->frame_count = 0;
1251 }
1252 _frame_count_total += infop->frame_count;
1253 }
1255 // Based on the stack information in the linked list, allocate memory
1256 // block to return and fill it from the info in the linked list.
1257 void
1258 VM_GetMultipleStackTraces::allocate_and_fill_stacks(jint thread_count) {
1259 // do I need to worry about alignment issues?
1260 jlong alloc_size = thread_count * sizeof(jvmtiStackInfo)
1261 + _frame_count_total * sizeof(jvmtiFrameInfo);
1262 env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1264 // pointers to move through the newly allocated space as it is filled in
1265 jvmtiStackInfo *si = _stack_info + thread_count; // bottom of stack info
1266 jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si; // is the top of frame info
1268 // copy information in resource area into allocated buffer
1269 // insert stack info backwards since linked list is backwards
1270 // insert frame info forwards
1271 // walk the StackInfoNodes
1272 for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {
1273 jint frame_count = sin->info.frame_count;
1274 size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
1275 --si;
1276 memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
1277 if (frames_size == 0) {
1278 si->frame_buffer = NULL;
1279 } else {
1280 memcpy(fi, sin->info.frame_buffer, frames_size);
1281 si->frame_buffer = fi; // point to the new allocated copy of the frames
1282 fi += frame_count;
1283 }
1284 }
1285 assert(si == _stack_info, "the last copied stack info must be the first record");
1286 assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1287 "the last copied frame info must be the last record");
1288 }
1291 void
1292 VM_GetThreadListStackTraces::doit() {
1293 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1295 ResourceMark rm;
1296 for (int i = 0; i < _thread_count; ++i) {
1297 jthread jt = _thread_list[i];
1298 oop thread_oop = JNIHandles::resolve_external_guard(jt);
1299 if (thread_oop == NULL || !thread_oop->is_a(SystemDictionary::Thread_klass())) {
1300 set_result(JVMTI_ERROR_INVALID_THREAD);
1301 return;
1302 }
1303 fill_frames(jt, java_lang_Thread::thread(thread_oop), thread_oop);
1304 }
1305 allocate_and_fill_stacks(_thread_count);
1306 }
1308 void
1309 VM_GetAllStackTraces::doit() {
1310 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1312 ResourceMark rm;
1313 _final_thread_count = 0;
1314 for (JavaThread *jt = Threads::first(); jt != NULL; jt = jt->next()) {
1315 oop thread_oop = jt->threadObj();
1316 if (thread_oop != NULL &&
1317 !jt->is_exiting() &&
1318 java_lang_Thread::is_alive(thread_oop) &&
1319 !jt->is_hidden_from_external_view()) {
1320 ++_final_thread_count;
1321 // Handle block of the calling thread is used to create local refs.
1322 fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
1323 jt, thread_oop);
1324 }
1325 }
1326 allocate_and_fill_stacks(_final_thread_count);
1327 }
1329 // Verifies that the top frame is a java frame in an expected state.
1330 // Deoptimizes frame if needed.
1331 // Checks that the frame method signature matches the return type (tos).
1332 // HandleMark must be defined in the caller only.
1333 // It is to keep a ret_ob_h handle alive after return to the caller.
1334 jvmtiError
1335 JvmtiEnvBase::check_top_frame(JavaThread* current_thread, JavaThread* java_thread,
1336 jvalue value, TosState tos, Handle* ret_ob_h) {
1337 ResourceMark rm(current_thread);
1339 vframe *vf = vframeFor(java_thread, 0);
1340 NULL_CHECK(vf, JVMTI_ERROR_NO_MORE_FRAMES);
1342 javaVFrame *jvf = (javaVFrame*) vf;
1343 if (!vf->is_java_frame() || jvf->method()->is_native()) {
1344 return JVMTI_ERROR_OPAQUE_FRAME;
1345 }
1347 // If the frame is a compiled one, need to deoptimize it.
1348 if (vf->is_compiled_frame()) {
1349 if (!vf->fr().can_be_deoptimized()) {
1350 return JVMTI_ERROR_OPAQUE_FRAME;
1351 }
1352 Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());
1353 }
1355 // Get information about method return type
1356 Symbol* signature = jvf->method()->signature();
1358 ResultTypeFinder rtf(signature);
1359 TosState fr_tos = as_TosState(rtf.type());
1360 if (fr_tos != tos) {
1361 if (tos != itos || (fr_tos != btos && fr_tos != ctos && fr_tos != stos)) {
1362 return JVMTI_ERROR_TYPE_MISMATCH;
1363 }
1364 }
1366 // Check that the jobject class matches the return type signature.
1367 jobject jobj = value.l;
1368 if (tos == atos && jobj != NULL) { // NULL reference is allowed
1369 Handle ob_h = Handle(current_thread, JNIHandles::resolve_external_guard(jobj));
1370 NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
1371 KlassHandle ob_kh = KlassHandle(current_thread, ob_h()->klass());
1372 NULL_CHECK(ob_kh, JVMTI_ERROR_INVALID_OBJECT);
1374 // Method return type signature.
1375 char* ty_sign = 1 + strchr(signature->as_C_string(), ')');
1377 if (!VM_GetOrSetLocal::is_assignable(ty_sign, Klass::cast(ob_kh()), current_thread)) {
1378 return JVMTI_ERROR_TYPE_MISMATCH;
1379 }
1380 *ret_ob_h = ob_h;
1381 }
1382 return JVMTI_ERROR_NONE;
1383 } /* end check_top_frame */
1386 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
1387 // Main difference is on the last stage in the interpreter.
1388 // The PopFrame stops method execution to continue execution
1389 // from the same method call instruction.
1390 // The ForceEarlyReturn forces return from method so the execution
1391 // continues at the bytecode following the method call.
1393 // Threads_lock NOT held, java_thread not protected by lock
1394 // java_thread - pre-checked
1396 jvmtiError
1397 JvmtiEnvBase::force_early_return(JavaThread* java_thread, jvalue value, TosState tos) {
1398 JavaThread* current_thread = JavaThread::current();
1399 HandleMark hm(current_thread);
1400 uint32_t debug_bits = 0;
1402 // retrieve or create the state
1403 JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1404 if (state == NULL) {
1405 return JVMTI_ERROR_THREAD_NOT_ALIVE;
1406 }
1408 // Check if java_thread is fully suspended
1409 if (!is_thread_fully_suspended(java_thread,
1410 true /* wait for suspend completion */,
1411 &debug_bits)) {
1412 return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1413 }
1415 // Check to see if a ForceEarlyReturn was already in progress
1416 if (state->is_earlyret_pending()) {
1417 // Probably possible for JVMTI clients to trigger this, but the
1418 // JPDA backend shouldn't allow this to happen
1419 return JVMTI_ERROR_INTERNAL;
1420 }
1421 {
1422 // The same as for PopFrame. Workaround bug:
1423 // 4812902: popFrame hangs if the method is waiting at a synchronize
1424 // Catch this condition and return an error to avoid hanging.
1425 // Now JVMTI spec allows an implementation to bail out with an opaque
1426 // frame error.
1427 OSThread* osThread = java_thread->osthread();
1428 if (osThread->get_state() == MONITOR_WAIT) {
1429 return JVMTI_ERROR_OPAQUE_FRAME;
1430 }
1431 }
1432 Handle ret_ob_h = Handle();
1433 jvmtiError err = check_top_frame(current_thread, java_thread, value, tos, &ret_ob_h);
1434 if (err != JVMTI_ERROR_NONE) {
1435 return err;
1436 }
1437 assert(tos != atos || value.l == NULL || ret_ob_h() != NULL,
1438 "return object oop must not be NULL if jobject is not NULL");
1440 // Update the thread state to reflect that the top frame must be
1441 // forced to return.
1442 // The current frame will be returned later when the suspended
1443 // thread is resumed and right before returning from VM to Java.
1444 // (see call_VM_base() in assembler_<cpu>.cpp).
1446 state->set_earlyret_pending();
1447 state->set_earlyret_oop(ret_ob_h());
1448 state->set_earlyret_value(value, tos);
1450 // Set pending step flag for this early return.
1451 // It is cleared when next step event is posted.
1452 state->set_pending_step_for_earlyret();
1454 return JVMTI_ERROR_NONE;
1455 } /* end force_early_return */
1457 void
1458 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
1459 if ( _error != JVMTI_ERROR_NONE) {
1460 // Error occurred in previous iteration so no need to add
1461 // to the list.
1462 return;
1463 }
1464 if (mon->owner() == _java_thread ) {
1465 // Filter out on stack monitors collected during stack walk.
1466 oop obj = (oop)mon->object();
1467 bool found = false;
1468 for (int j = 0; j < _owned_monitors_list->length(); j++) {
1469 jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
1470 oop check = JNIHandles::resolve(jobj);
1471 if (check == obj) {
1472 // On stack monitor already collected during the stack walk.
1473 found = true;
1474 break;
1475 }
1476 }
1477 if (found == false) {
1478 // This is off stack monitor (e.g. acquired via jni MonitorEnter).
1479 jvmtiError err;
1480 jvmtiMonitorStackDepthInfo *jmsdi;
1481 err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1482 if (err != JVMTI_ERROR_NONE) {
1483 _error = err;
1484 return;
1485 }
1486 Handle hobj(obj);
1487 jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
1488 // stack depth is unknown for this monitor.
1489 jmsdi->stack_depth = -1;
1490 _owned_monitors_list->append(jmsdi);
1491 }
1492 }
1493 }
1495 #endif // !JVMTI_KERNEL