Path: blob/master/src/hotspot/share/prims/jvmtiEnvBase.cpp
41145 views
/*1* Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classLoaderDataGraph.hpp"26#include "classfile/javaClasses.hpp"27#include "classfile/moduleEntry.hpp"28#include "jvmtifiles/jvmtiEnv.hpp"29#include "memory/iterator.hpp"30#include "memory/resourceArea.hpp"31#include "oops/klass.inline.hpp"32#include "oops/objArrayKlass.hpp"33#include "oops/objArrayOop.hpp"34#include "oops/oop.inline.hpp"35#include "oops/oopHandle.inline.hpp"36#include "prims/jvmtiEnvBase.hpp"37#include "prims/jvmtiEventController.inline.hpp"38#include "prims/jvmtiExtensions.hpp"39#include "prims/jvmtiImpl.hpp"40#include "prims/jvmtiManageCapabilities.hpp"41#include "prims/jvmtiTagMap.hpp"42#include "prims/jvmtiThreadState.inline.hpp"43#include "runtime/biasedLocking.hpp"44#include "runtime/deoptimization.hpp"45#include "runtime/frame.inline.hpp"46#include "runtime/handles.inline.hpp"47#include "runtime/interfaceSupport.inline.hpp"48#include "runtime/jfieldIDWorkaround.hpp"49#include "runtime/jniHandles.inline.hpp"50#include "runtime/objectMonitor.inline.hpp"51#include "runtime/osThread.hpp"52#include "runtime/signature.hpp"53#include "runtime/thread.inline.hpp"54#include "runtime/threadSMR.hpp"55#include "runtime/vframe.inline.hpp"56#include "runtime/vframe_hp.hpp"57#include "runtime/vmThread.hpp"58#include "runtime/vmOperations.hpp"596061///////////////////////////////////////////////////////////////62//63// JvmtiEnvBase64//6566JvmtiEnvBase* JvmtiEnvBase::_head_environment = NULL;6768bool JvmtiEnvBase::_globally_initialized = false;69volatile bool JvmtiEnvBase::_needs_clean_up = false;7071jvmtiPhase JvmtiEnvBase::_phase = JVMTI_PHASE_PRIMORDIAL;7273volatile int JvmtiEnvBase::_dying_thread_env_iteration_count = 0;7475extern jvmtiInterface_1_ jvmti_Interface;76extern jvmtiInterface_1_ jvmtiTrace_Interface;777879// perform initializations that must occur before any JVMTI environments80// are released but which should only be initialized once (no matter81// how many environments are created).82void83JvmtiEnvBase::globally_initialize() {84assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");85assert(_globally_initialized == false, "bad call");8687JvmtiManageCapabilities::initialize();8889// register extension functions and events90JvmtiExtensions::register_extensions();9192#ifdef JVMTI_TRACE93JvmtiTrace::initialize();94#endif9596_globally_initialized = true;97}9899100void101JvmtiEnvBase::initialize() {102assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");103104// Add this environment to the end of the environment list (order is important)105{106// This block of code must not contain any safepoints, as list deallocation107// (which occurs at a safepoint) cannot occur simultaneously with this list108// addition. Note: NoSafepointVerifier cannot, currently, be used before109// threads exist.110JvmtiEnvIterator it;111JvmtiEnvBase *previous_env = NULL;112for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {113previous_env = env;114}115if (previous_env == NULL) {116_head_environment = this;117} else {118previous_env->set_next_environment(this);119}120}121122if (_globally_initialized == false) {123globally_initialize();124}125}126127jvmtiPhase128JvmtiEnvBase::phase() {129// For the JVMTI environments possessed the can_generate_early_vmstart:130// replace JVMTI_PHASE_PRIMORDIAL with JVMTI_PHASE_START131if (_phase == JVMTI_PHASE_PRIMORDIAL &&132JvmtiExport::early_vmstart_recorded() &&133early_vmstart_env()) {134return JVMTI_PHASE_START;135}136return _phase; // Normal case137}138139bool140JvmtiEnvBase::is_valid() {141jint value = 0;142143// This object might not be a JvmtiEnvBase so we can't assume144// the _magic field is properly aligned. Get the value in a safe145// way and then check against JVMTI_MAGIC.146147switch (sizeof(_magic)) {148case 2:149value = Bytes::get_native_u2((address)&_magic);150break;151152case 4:153value = Bytes::get_native_u4((address)&_magic);154break;155156case 8:157value = Bytes::get_native_u8((address)&_magic);158break;159160default:161guarantee(false, "_magic field is an unexpected size");162}163164return value == JVMTI_MAGIC;165}166167168bool169JvmtiEnvBase::use_version_1_0_semantics() {170int major, minor, micro;171172JvmtiExport::decode_version_values(_version, &major, &minor, µ);173return major == 1 && minor == 0; // micro version doesn't matter here174}175176177bool178JvmtiEnvBase::use_version_1_1_semantics() {179int major, minor, micro;180181JvmtiExport::decode_version_values(_version, &major, &minor, µ);182return major == 1 && minor == 1; // micro version doesn't matter here183}184185bool186JvmtiEnvBase::use_version_1_2_semantics() {187int major, minor, micro;188189JvmtiExport::decode_version_values(_version, &major, &minor, µ);190return major == 1 && minor == 2; // micro version doesn't matter here191}192193194JvmtiEnvBase::JvmtiEnvBase(jint version) : _env_event_enable() {195_version = version;196_env_local_storage = NULL;197_tag_map = NULL;198_native_method_prefix_count = 0;199_native_method_prefixes = NULL;200_next = NULL;201_class_file_load_hook_ever_enabled = false;202203// Moot since ClassFileLoadHook not yet enabled.204// But "true" will give a more predictable ClassFileLoadHook behavior205// for environment creation during ClassFileLoadHook.206_is_retransformable = true;207208// all callbacks initially NULL209memset(&_event_callbacks,0,sizeof(jvmtiEventCallbacks));210211// all capabilities initially off212memset(&_current_capabilities, 0, sizeof(_current_capabilities));213214// all prohibited capabilities initially off215memset(&_prohibited_capabilities, 0, sizeof(_prohibited_capabilities));216217_magic = JVMTI_MAGIC;218219JvmtiEventController::env_initialize((JvmtiEnv*)this);220221#ifdef JVMTI_TRACE222_jvmti_external.functions = TraceJVMTI != NULL ? &jvmtiTrace_Interface : &jvmti_Interface;223#else224_jvmti_external.functions = &jvmti_Interface;225#endif226}227228229void230JvmtiEnvBase::dispose() {231232#ifdef JVMTI_TRACE233JvmtiTrace::shutdown();234#endif235236// Dispose of event info and let the event controller call us back237// in a locked state (env_dispose, below)238JvmtiEventController::env_dispose(this);239}240241void242JvmtiEnvBase::env_dispose() {243assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");244245// We have been entered with all events disabled on this environment.246// A race to re-enable events (by setting callbacks) is prevented by247// checking for a valid environment when setting callbacks (while248// holding the JvmtiThreadState_lock).249250// Mark as invalid.251_magic = DISPOSED_MAGIC;252253// Relinquish all capabilities.254jvmtiCapabilities *caps = get_capabilities();255JvmtiManageCapabilities::relinquish_capabilities(caps, caps, caps);256257// Same situation as with events (see above)258set_native_method_prefixes(0, NULL);259260JvmtiTagMap* tag_map_to_clear = tag_map_acquire();261// A tag map can be big, clear it now to save memory until262// the destructor runs.263if (tag_map_to_clear != NULL) {264tag_map_to_clear->clear();265}266267_needs_clean_up = true;268}269270271JvmtiEnvBase::~JvmtiEnvBase() {272assert(SafepointSynchronize::is_at_safepoint(), "sanity check");273274// There is a small window of time during which the tag map of a275// disposed environment could have been reallocated.276// Make sure it is gone.277JvmtiTagMap* tag_map_to_deallocate = _tag_map;278set_tag_map(NULL);279// A tag map can be big, deallocate it now280if (tag_map_to_deallocate != NULL) {281delete tag_map_to_deallocate;282}283284_magic = BAD_MAGIC;285}286287288void289JvmtiEnvBase::periodic_clean_up() {290assert(SafepointSynchronize::is_at_safepoint(), "sanity check");291292// JvmtiEnvBase reference is saved in JvmtiEnvThreadState. So293// clean up JvmtiThreadState before deleting JvmtiEnv pointer.294JvmtiThreadState::periodic_clean_up();295296// Unlink all invalid environments from the list of environments297// and deallocate them298JvmtiEnvIterator it;299JvmtiEnvBase* previous_env = NULL;300JvmtiEnvBase* env = it.first();301while (env != NULL) {302if (env->is_valid()) {303previous_env = env;304env = it.next(env);305} else {306// This one isn't valid, remove it from the list and deallocate it307JvmtiEnvBase* defunct_env = env;308env = it.next(env);309if (previous_env == NULL) {310_head_environment = env;311} else {312previous_env->set_next_environment(env);313}314delete defunct_env;315}316}317318}319320321void322JvmtiEnvBase::check_for_periodic_clean_up() {323assert(SafepointSynchronize::is_at_safepoint(), "sanity check");324325class ThreadInsideIterationClosure: public ThreadClosure {326private:327bool _inside;328public:329ThreadInsideIterationClosure() : _inside(false) {};330331void do_thread(Thread* thread) {332_inside |= thread->is_inside_jvmti_env_iteration();333}334335bool is_inside_jvmti_env_iteration() {336return _inside;337}338};339340if (_needs_clean_up) {341// Check if we are currently iterating environment,342// deallocation should not occur if we are343ThreadInsideIterationClosure tiic;344Threads::threads_do(&tiic);345if (!tiic.is_inside_jvmti_env_iteration() &&346!is_inside_dying_thread_env_iteration()) {347_needs_clean_up = false;348JvmtiEnvBase::periodic_clean_up();349}350}351}352353354void355JvmtiEnvBase::record_first_time_class_file_load_hook_enabled() {356assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),357"sanity check");358359if (!_class_file_load_hook_ever_enabled) {360_class_file_load_hook_ever_enabled = true;361362if (get_capabilities()->can_retransform_classes) {363_is_retransformable = true;364} else {365_is_retransformable = false;366367// cannot add retransform capability after ClassFileLoadHook has been enabled368get_prohibited_capabilities()->can_retransform_classes = 1;369}370}371}372373374void375JvmtiEnvBase::record_class_file_load_hook_enabled() {376if (!_class_file_load_hook_ever_enabled) {377if (Threads::number_of_threads() == 0) {378record_first_time_class_file_load_hook_enabled();379} else {380MutexLocker mu(JvmtiThreadState_lock);381record_first_time_class_file_load_hook_enabled();382}383}384}385386387jvmtiError388JvmtiEnvBase::set_native_method_prefixes(jint prefix_count, char** prefixes) {389assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),390"sanity check");391392int old_prefix_count = get_native_method_prefix_count();393char **old_prefixes = get_native_method_prefixes();394395// allocate and install the new prefixex396if (prefix_count == 0 || !is_valid()) {397_native_method_prefix_count = 0;398_native_method_prefixes = NULL;399} else {400// there are prefixes, allocate an array to hold them, and fill it401char** new_prefixes = (char**)os::malloc((prefix_count) * sizeof(char*), mtInternal);402if (new_prefixes == NULL) {403return JVMTI_ERROR_OUT_OF_MEMORY;404}405for (int i = 0; i < prefix_count; i++) {406char* prefix = prefixes[i];407if (prefix == NULL) {408for (int j = 0; j < (i-1); j++) {409os::free(new_prefixes[j]);410}411os::free(new_prefixes);412return JVMTI_ERROR_NULL_POINTER;413}414prefix = os::strdup(prefixes[i]);415if (prefix == NULL) {416for (int j = 0; j < (i-1); j++) {417os::free(new_prefixes[j]);418}419os::free(new_prefixes);420return JVMTI_ERROR_OUT_OF_MEMORY;421}422new_prefixes[i] = prefix;423}424_native_method_prefix_count = prefix_count;425_native_method_prefixes = new_prefixes;426}427428// now that we know the new prefixes have been successfully installed we can429// safely remove the old ones430if (old_prefix_count != 0) {431for (int i = 0; i < old_prefix_count; i++) {432os::free(old_prefixes[i]);433}434os::free(old_prefixes);435}436437return JVMTI_ERROR_NONE;438}439440441// Collect all the prefixes which have been set in any JVM TI environments442// by the SetNativeMethodPrefix(es) functions. Be sure to maintain the443// order of environments and the order of prefixes within each environment.444// Return in a resource allocated array.445char**446JvmtiEnvBase::get_all_native_method_prefixes(int* count_ptr) {447assert(Threads::number_of_threads() == 0 ||448SafepointSynchronize::is_at_safepoint() ||449JvmtiThreadState_lock->is_locked(),450"sanity check");451452int total_count = 0;453GrowableArray<char*>* prefix_array =new GrowableArray<char*>(5);454455JvmtiEnvIterator it;456for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {457int prefix_count = env->get_native_method_prefix_count();458char** prefixes = env->get_native_method_prefixes();459for (int j = 0; j < prefix_count; j++) {460// retrieve a prefix and so that it is safe against asynchronous changes461// copy it into the resource area462char* prefix = prefixes[j];463char* prefix_copy = NEW_RESOURCE_ARRAY(char, strlen(prefix)+1);464strcpy(prefix_copy, prefix);465prefix_array->at_put_grow(total_count++, prefix_copy);466}467}468469char** all_prefixes = NEW_RESOURCE_ARRAY(char*, total_count);470char** p = all_prefixes;471for (int i = 0; i < total_count; ++i) {472*p++ = prefix_array->at(i);473}474*count_ptr = total_count;475return all_prefixes;476}477478void479JvmtiEnvBase::set_event_callbacks(const jvmtiEventCallbacks* callbacks,480jint size_of_callbacks) {481assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");482483size_t byte_cnt = sizeof(jvmtiEventCallbacks);484485// clear in either case to be sure we got any gap between sizes486memset(&_event_callbacks, 0, byte_cnt);487488// Now that JvmtiThreadState_lock is held, prevent a possible race condition where events489// are re-enabled by a call to set event callbacks where the DisposeEnvironment490// occurs after the boiler-plate environment check and before the lock is acquired.491if (callbacks != NULL && is_valid()) {492if (size_of_callbacks < (jint)byte_cnt) {493byte_cnt = size_of_callbacks;494}495memcpy(&_event_callbacks, callbacks, byte_cnt);496}497}498499500// In the fullness of time, all users of the method should instead501// directly use allocate, besides being cleaner and faster, this will502// mean much better out of memory handling503unsigned char *504JvmtiEnvBase::jvmtiMalloc(jlong size) {505unsigned char* mem = NULL;506jvmtiError result = allocate(size, &mem);507assert(result == JVMTI_ERROR_NONE, "Allocate failed");508return mem;509}510511512// Handle management513514jobject JvmtiEnvBase::jni_reference(Handle hndl) {515return JNIHandles::make_local(hndl());516}517518jobject JvmtiEnvBase::jni_reference(JavaThread *thread, Handle hndl) {519return JNIHandles::make_local(thread, hndl());520}521522void JvmtiEnvBase::destroy_jni_reference(jobject jobj) {523JNIHandles::destroy_local(jobj);524}525526void JvmtiEnvBase::destroy_jni_reference(JavaThread *thread, jobject jobj) {527JNIHandles::destroy_local(jobj); // thread is unused.528}529530//531// Threads532//533534jobject *535JvmtiEnvBase::new_jobjectArray(int length, Handle *handles) {536if (length == 0) {537return NULL;538}539540jobject *objArray = (jobject *) jvmtiMalloc(sizeof(jobject) * length);541NULL_CHECK(objArray, NULL);542543for (int i=0; i<length; i++) {544objArray[i] = jni_reference(handles[i]);545}546return objArray;547}548549jthread *550JvmtiEnvBase::new_jthreadArray(int length, Handle *handles) {551return (jthread *) new_jobjectArray(length,handles);552}553554jthreadGroup *555JvmtiEnvBase::new_jthreadGroupArray(int length, Handle *handles) {556return (jthreadGroup *) new_jobjectArray(length,handles);557}558559// return the vframe on the specified thread and depth, NULL if no such frame560// The thread and the oops in the returned vframe might not have been process.561vframe*562JvmtiEnvBase::vframeForNoProcess(JavaThread* java_thread, jint depth) {563if (!java_thread->has_last_Java_frame()) {564return NULL;565}566RegisterMap reg_map(java_thread, true /* update_map */, false /* process_frames */);567vframe *vf = java_thread->last_java_vframe(®_map);568int d = 0;569while ((vf != NULL) && (d < depth)) {570vf = vf->java_sender();571d++;572}573return vf;574}575576577//578// utilities: JNI objects579//580581582jclass583JvmtiEnvBase::get_jni_class_non_null(Klass* k) {584assert(k != NULL, "k != NULL");585Thread *thread = Thread::current();586return (jclass)jni_reference(Handle(thread, k->java_mirror()));587}588589//590// Field Information591//592593bool594JvmtiEnvBase::get_field_descriptor(Klass* k, jfieldID field, fieldDescriptor* fd) {595if (!jfieldIDWorkaround::is_valid_jfieldID(k, field)) {596return false;597}598bool found = false;599if (jfieldIDWorkaround::is_static_jfieldID(field)) {600JNIid* id = jfieldIDWorkaround::from_static_jfieldID(field);601found = id->find_local_field(fd);602} else {603// Non-static field. The fieldID is really the offset of the field within the object.604int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);605found = InstanceKlass::cast(k)->find_field_from_offset(offset, false, fd);606}607return found;608}609610//611// Object Monitor Information612//613614//615// Count the number of objects for a lightweight monitor. The hobj616// parameter is object that owns the monitor so this routine will617// count the number of times the same object was locked by frames618// in java_thread.619//620jint621JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {622jint ret = 0;623if (!java_thread->has_last_Java_frame()) {624return ret; // no Java frames so no monitors625}626627Thread* current_thread = Thread::current();628ResourceMark rm(current_thread);629HandleMark hm(current_thread);630RegisterMap reg_map(java_thread);631632for(javaVFrame *jvf=java_thread->last_java_vframe(®_map); jvf != NULL;633jvf = jvf->java_sender()) {634GrowableArray<MonitorInfo*>* mons = jvf->monitors();635if (!mons->is_empty()) {636for (int i = 0; i < mons->length(); i++) {637MonitorInfo *mi = mons->at(i);638if (mi->owner_is_scalar_replaced()) continue;639640// see if owner of the monitor is our object641if (mi->owner() != NULL && mi->owner() == hobj()) {642ret++;643}644}645}646}647return ret;648}649650651652jvmtiError653JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread, jobject *monitor_ptr) {654Thread *current_thread = Thread::current();655assert(java_thread->is_handshake_safe_for(current_thread),656"call by myself or at handshake");657oop obj = NULL;658// The ObjectMonitor* can't be async deflated since we are either659// at a safepoint or the calling thread is operating on itself so660// it cannot leave the underlying wait()/enter() call.661ObjectMonitor *mon = java_thread->current_waiting_monitor();662if (mon == NULL) {663// thread is not doing an Object.wait() call664mon = java_thread->current_pending_monitor();665if (mon != NULL) {666// The thread is trying to enter() an ObjectMonitor.667obj = mon->object();668assert(obj != NULL, "ObjectMonitor should have a valid object!");669}670// implied else: no contended ObjectMonitor671} else {672// thread is doing an Object.wait() call673obj = mon->object();674assert(obj != NULL, "Object.wait() should have an object");675}676677if (obj == NULL) {678*monitor_ptr = NULL;679} else {680HandleMark hm(current_thread);681Handle hobj(current_thread, obj);682*monitor_ptr = jni_reference(calling_thread, hobj);683}684return JVMTI_ERROR_NONE;685}686687688jvmtiError689JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,690GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {691// Note:692// calling_thread is the thread that requested the list of monitors for java_thread.693// java_thread is the thread owning the monitors.694// current_thread is the thread executing this code, can be a non-JavaThread (e.g. VM Thread).695// And they all may be different threads.696jvmtiError err = JVMTI_ERROR_NONE;697Thread *current_thread = Thread::current();698assert(java_thread->is_handshake_safe_for(current_thread),699"call by myself or at handshake");700701if (java_thread->has_last_Java_frame()) {702ResourceMark rm(current_thread);703HandleMark hm(current_thread);704RegisterMap reg_map(java_thread);705706int depth = 0;707for (javaVFrame *jvf = java_thread->last_java_vframe(®_map); jvf != NULL;708jvf = jvf->java_sender()) {709if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) { // check for stack too deep710// add locked objects for this frame into list711err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);712if (err != JVMTI_ERROR_NONE) {713return err;714}715}716}717}718719// Get off stack monitors. (e.g. acquired via jni MonitorEnter).720JvmtiMonitorClosure jmc(java_thread, calling_thread, owned_monitors_list, this);721ObjectSynchronizer::monitors_iterate(&jmc);722err = jmc.error();723724return err;725}726727// Save JNI local handles for any objects that this frame owns.728jvmtiError729JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,730javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, jint stack_depth) {731jvmtiError err = JVMTI_ERROR_NONE;732Thread* current_thread = Thread::current();733ResourceMark rm(current_thread);734HandleMark hm(current_thread);735736GrowableArray<MonitorInfo*>* mons = jvf->monitors();737if (mons->is_empty()) {738return err; // this javaVFrame holds no monitors739}740741oop wait_obj = NULL;742{743// The ObjectMonitor* can't be async deflated since we are either744// at a safepoint or the calling thread is operating on itself so745// it cannot leave the underlying wait() call.746// Save object of current wait() call (if any) for later comparison.747ObjectMonitor *mon = java_thread->current_waiting_monitor();748if (mon != NULL) {749wait_obj = mon->object();750}751}752oop pending_obj = NULL;753{754// The ObjectMonitor* can't be async deflated since we are either755// at a safepoint or the calling thread is operating on itself so756// it cannot leave the underlying enter() call.757// Save object of current enter() call (if any) for later comparison.758ObjectMonitor *mon = java_thread->current_pending_monitor();759if (mon != NULL) {760pending_obj = mon->object();761}762}763764for (int i = 0; i < mons->length(); i++) {765MonitorInfo *mi = mons->at(i);766767if (mi->owner_is_scalar_replaced()) continue;768769oop obj = mi->owner();770if (obj == NULL) {771// this monitor doesn't have an owning object so skip it772continue;773}774775if (wait_obj == obj) {776// the thread is waiting on this monitor so it isn't really owned777continue;778}779780if (pending_obj == obj) {781// the thread is pending on this monitor so it isn't really owned782continue;783}784785if (owned_monitors_list->length() > 0) {786// Our list has at least one object on it so we have to check787// for recursive object locking788bool found = false;789for (int j = 0; j < owned_monitors_list->length(); j++) {790jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;791oop check = JNIHandles::resolve(jobj);792if (check == obj) {793found = true; // we found the object794break;795}796}797798if (found) {799// already have this object so don't include it800continue;801}802}803804// add the owning object to our list805jvmtiMonitorStackDepthInfo *jmsdi;806err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);807if (err != JVMTI_ERROR_NONE) {808return err;809}810Handle hobj(Thread::current(), obj);811jmsdi->monitor = jni_reference(calling_thread, hobj);812jmsdi->stack_depth = stack_depth;813owned_monitors_list->append(jmsdi);814}815816return err;817}818819jvmtiError820JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,821jint start_depth, jint max_count,822jvmtiFrameInfo* frame_buffer, jint* count_ptr) {823#ifdef ASSERT824uint32_t debug_bits = 0;825#endif826Thread *current_thread = Thread::current();827assert(SafepointSynchronize::is_at_safepoint() ||828java_thread->is_handshake_safe_for(current_thread),829"call by myself / at safepoint / at handshake");830int count = 0;831if (java_thread->has_last_Java_frame()) {832RegisterMap reg_map(java_thread);833ResourceMark rm(current_thread);834javaVFrame *jvf = java_thread->last_java_vframe(®_map);835HandleMark hm(current_thread);836if (start_depth != 0) {837if (start_depth > 0) {838for (int j = 0; j < start_depth && jvf != NULL; j++) {839jvf = jvf->java_sender();840}841if (jvf == NULL) {842// start_depth is deeper than the stack depth843return JVMTI_ERROR_ILLEGAL_ARGUMENT;844}845} else { // start_depth < 0846// we are referencing the starting depth based on the oldest847// part of the stack.848// optimize to limit the number of times that java_sender() is called849javaVFrame *jvf_cursor = jvf;850javaVFrame *jvf_prev = NULL;851javaVFrame *jvf_prev_prev = NULL;852int j = 0;853while (jvf_cursor != NULL) {854jvf_prev_prev = jvf_prev;855jvf_prev = jvf_cursor;856for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {857jvf_cursor = jvf_cursor->java_sender();858}859}860if (j == start_depth) {861// previous pointer is exactly where we want to start862jvf = jvf_prev;863} else {864// we need to back up further to get to the right place865if (jvf_prev_prev == NULL) {866// the -start_depth is greater than the stack depth867return JVMTI_ERROR_ILLEGAL_ARGUMENT;868}869// j now is the number of frames on the stack starting with870// jvf_prev, we start from jvf_prev_prev and move older on871// the stack that many, the result is -start_depth frames872// remaining.873jvf = jvf_prev_prev;874for (; j < 0; j++) {875jvf = jvf->java_sender();876}877}878}879}880for (; count < max_count && jvf != NULL; count++) {881frame_buffer[count].method = jvf->method()->jmethod_id();882frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());883jvf = jvf->java_sender();884}885} else {886if (start_depth != 0) {887// no frames and there is a starting depth888return JVMTI_ERROR_ILLEGAL_ARGUMENT;889}890}891*count_ptr = count;892return JVMTI_ERROR_NONE;893}894895jvmtiError896JvmtiEnvBase::get_frame_count(JvmtiThreadState *state, jint *count_ptr) {897assert((state != NULL),898"JavaThread should create JvmtiThreadState before calling this method");899*count_ptr = state->count_frames();900return JVMTI_ERROR_NONE;901}902903jvmtiError904JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,905jmethodID* method_ptr, jlocation* location_ptr) {906#ifdef ASSERT907uint32_t debug_bits = 0;908#endif909Thread* current_thread = Thread::current();910assert(java_thread->is_handshake_safe_for(current_thread),911"call by myself or at handshake");912ResourceMark rm(current_thread);913914vframe *vf = vframeForNoProcess(java_thread, depth);915if (vf == NULL) {916return JVMTI_ERROR_NO_MORE_FRAMES;917}918919// vframeFor should return a java frame. If it doesn't920// it means we've got an internal error and we return the921// error in product mode. In debug mode we will instead922// attempt to cast the vframe to a javaVFrame and will923// cause an assertion/crash to allow further diagnosis.924#ifdef PRODUCT925if (!vf->is_java_frame()) {926return JVMTI_ERROR_INTERNAL;927}928#endif929930HandleMark hm(current_thread);931javaVFrame *jvf = javaVFrame::cast(vf);932Method* method = jvf->method();933if (method->is_native()) {934*location_ptr = -1;935} else {936*location_ptr = jvf->bci();937}938*method_ptr = method->jmethod_id();939940return JVMTI_ERROR_NONE;941}942943944jvmtiError945JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {946assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");947Thread* current_thread = VMThread::vm_thread();948assert(current_thread == Thread::current(), "must be");949950HandleMark hm(current_thread);951Handle hobj;952953// Check arguments954{955oop mirror = JNIHandles::resolve_external_guard(object);956NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);957NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);958959hobj = Handle(current_thread, mirror);960}961962ThreadsListHandle tlh(current_thread);963JavaThread *owning_thread = NULL;964ObjectMonitor *mon = NULL;965jvmtiMonitorUsage ret = {966NULL, 0, 0, NULL, 0, NULL967};968969uint32_t debug_bits = 0;970// first derive the object's owner and entry_count (if any)971{972// Revoke any biases before querying the mark word973BiasedLocking::revoke_at_safepoint(hobj);974975address owner = NULL;976{977markWord mark = hobj()->mark();978979if (!mark.has_monitor()) {980// this object has a lightweight monitor981982if (mark.has_locker()) {983owner = (address)mark.locker(); // save the address of the Lock word984}985// implied else: no owner986} else {987// this object has a heavyweight monitor988mon = mark.monitor();989990// The owner field of a heavyweight monitor may be NULL for no991// owner, a JavaThread * or it may still be the address of the992// Lock word in a JavaThread's stack. A monitor can be inflated993// by a non-owning JavaThread, but only the owning JavaThread994// can change the owner field from the Lock word to the995// JavaThread * and it may not have done that yet.996owner = (address)mon->owner();997}998}9991000if (owner != NULL) {1001// This monitor is owned so we have to find the owning JavaThread.1002owning_thread = Threads::owning_thread_from_monitor_owner(tlh.list(), owner);1003assert(owning_thread != NULL, "owning JavaThread must not be NULL");1004Handle th(current_thread, owning_thread->threadObj());1005ret.owner = (jthread)jni_reference(calling_thread, th);1006}10071008if (owning_thread != NULL) { // monitor is owned1009// The recursions field of a monitor does not reflect recursions1010// as lightweight locks before inflating the monitor are not included.1011// We have to count the number of recursive monitor entries the hard way.1012// We pass a handle to survive any GCs along the way.1013ret.entry_count = count_locked_objects(owning_thread, hobj);1014}1015// implied else: entry_count == 01016}10171018jint nWant = 0, nWait = 0;1019if (mon != NULL) {1020// this object has a heavyweight monitor1021nWant = mon->contentions(); // # of threads contending for monitor1022nWait = mon->waiters(); // # of threads in Object.wait()1023ret.waiter_count = nWant + nWait;1024ret.notify_waiter_count = nWait;1025} else {1026// this object has a lightweight monitor1027ret.waiter_count = 0;1028ret.notify_waiter_count = 0;1029}10301031// Allocate memory for heavyweight and lightweight monitor.1032jvmtiError err;1033err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);1034if (err != JVMTI_ERROR_NONE) {1035return err;1036}1037err = allocate(ret.notify_waiter_count * sizeof(jthread *),1038(unsigned char**)&ret.notify_waiters);1039if (err != JVMTI_ERROR_NONE) {1040deallocate((unsigned char*)ret.waiters);1041return err;1042}10431044// now derive the rest of the fields1045if (mon != NULL) {1046// this object has a heavyweight monitor10471048// Number of waiters may actually be less than the waiter count.1049// So NULL out memory so that unused memory will be NULL.1050memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));1051memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));10521053if (ret.waiter_count > 0) {1054// we have contending and/or waiting threads1055if (nWant > 0) {1056// we have contending threads1057ResourceMark rm(current_thread);1058// get_pending_threads returns only java thread so we do not need to1059// check for non java threads.1060GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(tlh.list(), nWant, (address)mon);1061if (wantList->length() < nWant) {1062// robustness: the pending list has gotten smaller1063nWant = wantList->length();1064}1065for (int i = 0; i < nWant; i++) {1066JavaThread *pending_thread = wantList->at(i);1067Handle th(current_thread, pending_thread->threadObj());1068ret.waiters[i] = (jthread)jni_reference(calling_thread, th);1069}1070}1071if (nWait > 0) {1072// we have threads in Object.wait()1073int offset = nWant; // add after any contending threads1074ObjectWaiter *waiter = mon->first_waiter();1075for (int i = 0, j = 0; i < nWait; i++) {1076if (waiter == NULL) {1077// robustness: the waiting list has gotten smaller1078nWait = j;1079break;1080}1081JavaThread *w = mon->thread_of_waiter(waiter);1082if (w != NULL) {1083// If the thread was found on the ObjectWaiter list, then1084// it has not been notified. This thread can't change the1085// state of the monitor so it doesn't need to be suspended.1086Handle th(current_thread, w->threadObj());1087ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);1088ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);1089}1090waiter = mon->next_waiter(waiter);1091}1092}1093} // ThreadsListHandle is destroyed here.10941095// Adjust count. nWant and nWait count values may be less than original.1096ret.waiter_count = nWant + nWait;1097ret.notify_waiter_count = nWait;1098} else {1099// this object has a lightweight monitor and we have nothing more1100// to do here because the defaults are just fine.1101}11021103// we don't update return parameter unless everything worked1104*info_ptr = ret;11051106return JVMTI_ERROR_NONE;1107}11081109ResourceTracker::ResourceTracker(JvmtiEnv* env) {1110_env = env;1111_allocations = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<unsigned char*>(20, mtServiceability);1112_failed = false;1113}1114ResourceTracker::~ResourceTracker() {1115if (_failed) {1116for (int i=0; i<_allocations->length(); i++) {1117_env->deallocate(_allocations->at(i));1118}1119}1120delete _allocations;1121}11221123jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {1124unsigned char *ptr;1125jvmtiError err = _env->allocate(size, &ptr);1126if (err == JVMTI_ERROR_NONE) {1127_allocations->append(ptr);1128*mem_ptr = ptr;1129} else {1130*mem_ptr = NULL;1131_failed = true;1132}1133return err;1134}11351136unsigned char* ResourceTracker::allocate(jlong size) {1137unsigned char* ptr;1138allocate(size, &ptr);1139return ptr;1140}11411142char* ResourceTracker::strdup(const char* str) {1143char *dup_str = (char*)allocate(strlen(str)+1);1144if (dup_str != NULL) {1145strcpy(dup_str, str);1146}1147return dup_str;1148}11491150struct StackInfoNode {1151struct StackInfoNode *next;1152jvmtiStackInfo info;1153};11541155// Create a jvmtiStackInfo inside a linked list node and create a1156// buffer for the frame information, both allocated as resource objects.1157// Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.1158// Note that either or both of thr and thread_oop1159// may be null if the thread is new or has exited.1160void1161MultipleStackTracesCollector::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {1162#ifdef ASSERT1163Thread *current_thread = Thread::current();1164assert(SafepointSynchronize::is_at_safepoint() ||1165thr->is_handshake_safe_for(current_thread),1166"call by myself / at safepoint / at handshake");1167#endif11681169jint state = 0;1170struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);1171jvmtiStackInfo *infop = &(node->info);1172node->next = head();1173set_head(node);1174infop->frame_count = 0;1175infop->thread = jt;11761177if (thread_oop != NULL) {1178// get most state bits1179state = (jint)java_lang_Thread::get_thread_status(thread_oop);1180}11811182if (thr != NULL) { // add more state bits if there is a JavaThead to query1183if (thr->is_suspended()) {1184state |= JVMTI_THREAD_STATE_SUSPENDED;1185}1186JavaThreadState jts = thr->thread_state();1187if (jts == _thread_in_native) {1188state |= JVMTI_THREAD_STATE_IN_NATIVE;1189}1190if (thr->is_interrupted(false)) {1191state |= JVMTI_THREAD_STATE_INTERRUPTED;1192}1193}1194infop->state = state;11951196if (thr != NULL && (state & JVMTI_THREAD_STATE_ALIVE) != 0) {1197infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());1198env()->get_stack_trace(thr, 0, max_frame_count(),1199infop->frame_buffer, &(infop->frame_count));1200} else {1201infop->frame_buffer = NULL;1202infop->frame_count = 0;1203}1204_frame_count_total += infop->frame_count;1205}12061207// Based on the stack information in the linked list, allocate memory1208// block to return and fill it from the info in the linked list.1209void1210MultipleStackTracesCollector::allocate_and_fill_stacks(jint thread_count) {1211// do I need to worry about alignment issues?1212jlong alloc_size = thread_count * sizeof(jvmtiStackInfo)1213+ _frame_count_total * sizeof(jvmtiFrameInfo);1214env()->allocate(alloc_size, (unsigned char **)&_stack_info);12151216// pointers to move through the newly allocated space as it is filled in1217jvmtiStackInfo *si = _stack_info + thread_count; // bottom of stack info1218jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si; // is the top of frame info12191220// copy information in resource area into allocated buffer1221// insert stack info backwards since linked list is backwards1222// insert frame info forwards1223// walk the StackInfoNodes1224for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {1225jint frame_count = sin->info.frame_count;1226size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);1227--si;1228memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));1229if (frames_size == 0) {1230si->frame_buffer = NULL;1231} else {1232memcpy(fi, sin->info.frame_buffer, frames_size);1233si->frame_buffer = fi; // point to the new allocated copy of the frames1234fi += frame_count;1235}1236}1237assert(si == _stack_info, "the last copied stack info must be the first record");1238assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,1239"the last copied frame info must be the last record");1240}124112421243void1244VM_GetThreadListStackTraces::doit() {1245assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");12461247ResourceMark rm;1248ThreadsListHandle tlh;1249for (int i = 0; i < _thread_count; ++i) {1250jthread jt = _thread_list[i];1251JavaThread* java_thread = NULL;1252oop thread_oop = NULL;1253jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), jt, &java_thread, &thread_oop);1254if (err != JVMTI_ERROR_NONE) {1255// We got an error code so we don't have a JavaThread *, but1256// only return an error from here if we didn't get a valid1257// thread_oop.1258if (thread_oop == NULL) {1259_collector.set_result(err);1260return;1261}1262// We have a valid thread_oop.1263}1264_collector.fill_frames(jt, java_thread, thread_oop);1265}1266_collector.allocate_and_fill_stacks(_thread_count);1267}12681269void1270GetSingleStackTraceClosure::do_thread(Thread *target) {1271JavaThread *jt = target->as_Java_thread();1272oop thread_oop = jt->threadObj();12731274if (!jt->is_exiting() && thread_oop != NULL) {1275ResourceMark rm;1276_collector.fill_frames(_jthread, jt, thread_oop);1277_collector.allocate_and_fill_stacks(1);1278}1279}12801281void1282VM_GetAllStackTraces::doit() {1283assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");12841285ResourceMark rm;1286_final_thread_count = 0;1287for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {1288oop thread_oop = jt->threadObj();1289if (thread_oop != NULL &&1290!jt->is_exiting() &&1291java_lang_Thread::is_alive(thread_oop) &&1292!jt->is_hidden_from_external_view()) {1293++_final_thread_count;1294// Handle block of the calling thread is used to create local refs.1295_collector.fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),1296jt, thread_oop);1297}1298}1299_collector.allocate_and_fill_stacks(_final_thread_count);1300}13011302// Verifies that the top frame is a java frame in an expected state.1303// Deoptimizes frame if needed.1304// Checks that the frame method signature matches the return type (tos).1305// HandleMark must be defined in the caller only.1306// It is to keep a ret_ob_h handle alive after return to the caller.1307jvmtiError1308JvmtiEnvBase::check_top_frame(Thread* current_thread, JavaThread* java_thread,1309jvalue value, TosState tos, Handle* ret_ob_h) {1310ResourceMark rm(current_thread);13111312vframe *vf = vframeForNoProcess(java_thread, 0);1313NULL_CHECK(vf, JVMTI_ERROR_NO_MORE_FRAMES);13141315javaVFrame *jvf = (javaVFrame*) vf;1316if (!vf->is_java_frame() || jvf->method()->is_native()) {1317return JVMTI_ERROR_OPAQUE_FRAME;1318}13191320// If the frame is a compiled one, need to deoptimize it.1321if (vf->is_compiled_frame()) {1322if (!vf->fr().can_be_deoptimized()) {1323return JVMTI_ERROR_OPAQUE_FRAME;1324}1325Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());1326}13271328// Get information about method return type1329Symbol* signature = jvf->method()->signature();13301331ResultTypeFinder rtf(signature);1332TosState fr_tos = as_TosState(rtf.type());1333if (fr_tos != tos) {1334if (tos != itos || (fr_tos != btos && fr_tos != ztos && fr_tos != ctos && fr_tos != stos)) {1335return JVMTI_ERROR_TYPE_MISMATCH;1336}1337}13381339// Check that the jobject class matches the return type signature.1340jobject jobj = value.l;1341if (tos == atos && jobj != NULL) { // NULL reference is allowed1342Handle ob_h(current_thread, JNIHandles::resolve_external_guard(jobj));1343NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);1344Klass* ob_k = ob_h()->klass();1345NULL_CHECK(ob_k, JVMTI_ERROR_INVALID_OBJECT);13461347// Method return type signature.1348char* ty_sign = 1 + strchr(signature->as_C_string(), JVM_SIGNATURE_ENDFUNC);13491350if (!VM_GetOrSetLocal::is_assignable(ty_sign, ob_k, current_thread)) {1351return JVMTI_ERROR_TYPE_MISMATCH;1352}1353*ret_ob_h = ob_h;1354}1355return JVMTI_ERROR_NONE;1356} /* end check_top_frame */135713581359// ForceEarlyReturn<type> follows the PopFrame approach in many aspects.1360// Main difference is on the last stage in the interpreter.1361// The PopFrame stops method execution to continue execution1362// from the same method call instruction.1363// The ForceEarlyReturn forces return from method so the execution1364// continues at the bytecode following the method call.13651366// java_thread - protected by ThreadsListHandle and pre-checked13671368jvmtiError1369JvmtiEnvBase::force_early_return(JavaThread* java_thread, jvalue value, TosState tos) {1370// retrieve or create the state1371JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);1372if (state == NULL) {1373return JVMTI_ERROR_THREAD_NOT_ALIVE;1374}13751376// Eagerly reallocate scalar replaced objects.1377JavaThread* current_thread = JavaThread::current();1378EscapeBarrier eb(true, current_thread, java_thread);1379if (!eb.deoptimize_objects(0)) {1380// Reallocation of scalar replaced objects failed -> return with error1381return JVMTI_ERROR_OUT_OF_MEMORY;1382}13831384SetForceEarlyReturn op(state, value, tos);1385if (java_thread == current_thread) {1386op.doit(java_thread, true /* self */);1387} else {1388Handshake::execute(&op, java_thread);1389}1390return op.result();1391}13921393void1394SetForceEarlyReturn::doit(Thread *target, bool self) {1395JavaThread* java_thread = target->as_Java_thread();1396Thread* current_thread = Thread::current();1397HandleMark hm(current_thread);13981399if (!self) {1400if (!java_thread->is_suspended()) {1401_result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;1402return;1403}1404}14051406// Check to see if a ForceEarlyReturn was already in progress1407if (_state->is_earlyret_pending()) {1408// Probably possible for JVMTI clients to trigger this, but the1409// JPDA backend shouldn't allow this to happen1410_result = JVMTI_ERROR_INTERNAL;1411return;1412}1413{1414// The same as for PopFrame. Workaround bug:1415// 4812902: popFrame hangs if the method is waiting at a synchronize1416// Catch this condition and return an error to avoid hanging.1417// Now JVMTI spec allows an implementation to bail out with an opaque1418// frame error.1419OSThread* osThread = java_thread->osthread();1420if (osThread->get_state() == MONITOR_WAIT) {1421_result = JVMTI_ERROR_OPAQUE_FRAME;1422return;1423}1424}14251426Handle ret_ob_h;1427_result = JvmtiEnvBase::check_top_frame(current_thread, java_thread, _value, _tos, &ret_ob_h);1428if (_result != JVMTI_ERROR_NONE) {1429return;1430}1431assert(_tos != atos || _value.l == NULL || ret_ob_h() != NULL,1432"return object oop must not be NULL if jobject is not NULL");14331434// Update the thread state to reflect that the top frame must be1435// forced to return.1436// The current frame will be returned later when the suspended1437// thread is resumed and right before returning from VM to Java.1438// (see call_VM_base() in assembler_<cpu>.cpp).14391440_state->set_earlyret_pending();1441_state->set_earlyret_oop(ret_ob_h());1442_state->set_earlyret_value(_value, _tos);14431444// Set pending step flag for this early return.1445// It is cleared when next step event is posted.1446_state->set_pending_step_for_earlyret();1447}14481449void1450JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {1451if ( _error != JVMTI_ERROR_NONE) {1452// Error occurred in previous iteration so no need to add1453// to the list.1454return;1455}1456if (mon->owner() == _java_thread ) {1457// Filter out on stack monitors collected during stack walk.1458oop obj = mon->object();1459bool found = false;1460for (int j = 0; j < _owned_monitors_list->length(); j++) {1461jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;1462oop check = JNIHandles::resolve(jobj);1463if (check == obj) {1464// On stack monitor already collected during the stack walk.1465found = true;1466break;1467}1468}1469if (found == false) {1470// This is off stack monitor (e.g. acquired via jni MonitorEnter).1471jvmtiError err;1472jvmtiMonitorStackDepthInfo *jmsdi;1473err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);1474if (err != JVMTI_ERROR_NONE) {1475_error = err;1476return;1477}1478Handle hobj(Thread::current(), obj);1479jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);1480// stack depth is unknown for this monitor.1481jmsdi->stack_depth = -1;1482_owned_monitors_list->append(jmsdi);1483}1484}1485}14861487GrowableArray<OopHandle>* JvmtiModuleClosure::_tbl = NULL;14881489void JvmtiModuleClosure::do_module(ModuleEntry* entry) {1490assert_locked_or_safepoint(Module_lock);1491OopHandle module = entry->module_handle();1492guarantee(module.resolve() != NULL, "module object is NULL");1493_tbl->push(module);1494}14951496jvmtiError1497JvmtiModuleClosure::get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr) {1498ResourceMark rm;1499MutexLocker mcld(ClassLoaderDataGraph_lock);1500MutexLocker ml(Module_lock);15011502_tbl = new GrowableArray<OopHandle>(77);1503if (_tbl == NULL) {1504return JVMTI_ERROR_OUT_OF_MEMORY;1505}15061507// Iterate over all the modules loaded to the system.1508ClassLoaderDataGraph::modules_do(&do_module);15091510jint len = _tbl->length();1511guarantee(len > 0, "at least one module must be present");15121513jobject* array = (jobject*)env->jvmtiMalloc((jlong)(len * sizeof(jobject)));1514if (array == NULL) {1515return JVMTI_ERROR_OUT_OF_MEMORY;1516}1517for (jint idx = 0; idx < len; idx++) {1518array[idx] = JNIHandles::make_local(Thread::current(), _tbl->at(idx).resolve());1519}1520_tbl = NULL;1521*modules_ptr = array;1522*module_count_ptr = len;1523return JVMTI_ERROR_NONE;1524}15251526void1527UpdateForPopTopFrameClosure::doit(Thread *target, bool self) {1528Thread* current_thread = Thread::current();1529HandleMark hm(current_thread);1530JavaThread* java_thread = target->as_Java_thread();1531assert(java_thread == _state->get_thread(), "Must be");15321533if (!self && !java_thread->is_suspended()) {1534_result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;1535return;1536}15371538// Check to see if a PopFrame was already in progress1539if (java_thread->popframe_condition() != JavaThread::popframe_inactive) {1540// Probably possible for JVMTI clients to trigger this, but the1541// JPDA backend shouldn't allow this to happen1542_result = JVMTI_ERROR_INTERNAL;1543return;1544}15451546// Was workaround bug1547// 4812902: popFrame hangs if the method is waiting at a synchronize1548// Catch this condition and return an error to avoid hanging.1549// Now JVMTI spec allows an implementation to bail out with an opaque frame error.1550OSThread* osThread = java_thread->osthread();1551if (osThread->get_state() == MONITOR_WAIT) {1552_result = JVMTI_ERROR_OPAQUE_FRAME;1553return;1554}15551556ResourceMark rm(current_thread);1557// Check if there is more than one Java frame in this thread, that the top two frames1558// are Java (not native) frames, and that there is no intervening VM frame1559int frame_count = 0;1560bool is_interpreted[2];1561intptr_t *frame_sp[2];1562// The 2-nd arg of constructor is needed to stop iterating at java entry frame.1563for (vframeStream vfs(java_thread, true, false /* process_frames */); !vfs.at_end(); vfs.next()) {1564methodHandle mh(current_thread, vfs.method());1565if (mh->is_native()) {1566_result = JVMTI_ERROR_OPAQUE_FRAME;1567return;1568}1569is_interpreted[frame_count] = vfs.is_interpreted_frame();1570frame_sp[frame_count] = vfs.frame_id();1571if (++frame_count > 1) break;1572}1573if (frame_count < 2) {1574// We haven't found two adjacent non-native Java frames on the top.1575// There can be two situations here:1576// 1. There are no more java frames1577// 2. Two top java frames are separated by non-java native frames1578if(JvmtiEnvBase::vframeForNoProcess(java_thread, 1) == NULL) {1579_result = JVMTI_ERROR_NO_MORE_FRAMES;1580return;1581} else {1582// Intervening non-java native or VM frames separate java frames.1583// Current implementation does not support this. See bug #5031735.1584// In theory it is possible to pop frames in such cases.1585_result = JVMTI_ERROR_OPAQUE_FRAME;1586return;1587}1588}15891590// If any of the top 2 frames is a compiled one, need to deoptimize it1591for (int i = 0; i < 2; i++) {1592if (!is_interpreted[i]) {1593Deoptimization::deoptimize_frame(java_thread, frame_sp[i]);1594}1595}15961597// Update the thread state to reflect that the top frame is popped1598// so that cur_stack_depth is maintained properly and all frameIDs1599// are invalidated.1600// The current frame will be popped later when the suspended thread1601// is resumed and right before returning from VM to Java.1602// (see call_VM_base() in assembler_<cpu>.cpp).16031604// It's fine to update the thread state here because no JVMTI events1605// shall be posted for this PopFrame.16061607if (!java_thread->is_exiting() && java_thread->threadObj() != NULL) {1608_state->update_for_pop_top_frame();1609java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);1610// Set pending step flag for this popframe and it is cleared when next1611// step event is posted.1612_state->set_pending_step_for_popframe();1613_result = JVMTI_ERROR_NONE;1614}1615}16161617void1618SetFramePopClosure::doit(Thread *target, bool self) {1619ResourceMark rm;1620JavaThread* java_thread = target->as_Java_thread();16211622assert(_state->get_thread() == java_thread, "Must be");16231624if (!self && !java_thread->is_suspended()) {1625_result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;1626return;1627}16281629vframe *vf = JvmtiEnvBase::vframeForNoProcess(java_thread, _depth);1630if (vf == NULL) {1631_result = JVMTI_ERROR_NO_MORE_FRAMES;1632return;1633}16341635if (!vf->is_java_frame() || ((javaVFrame*) vf)->method()->is_native()) {1636_result = JVMTI_ERROR_OPAQUE_FRAME;1637return;1638}16391640assert(vf->frame_pointer() != NULL, "frame pointer mustn't be NULL");1641if (java_thread->is_exiting() || java_thread->threadObj() == NULL) {1642return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */1643}1644int frame_number = _state->count_frames() - _depth;1645_state->env_thread_state((JvmtiEnvBase*)_env)->set_frame_pop(frame_number);1646_result = JVMTI_ERROR_NONE;1647}16481649void1650GetOwnedMonitorInfoClosure::do_thread(Thread *target) {1651JavaThread *jt = target->as_Java_thread();1652if (!jt->is_exiting() && (jt->threadObj() != NULL)) {1653_result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread,1654jt,1655_owned_monitors_list);1656}1657}16581659void1660GetCurrentContendedMonitorClosure::do_thread(Thread *target) {1661JavaThread *jt = target->as_Java_thread();1662if (!jt->is_exiting() && (jt->threadObj() != NULL)) {1663_result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor(_calling_thread,1664jt,1665_owned_monitor_ptr);1666}1667}16681669void1670GetStackTraceClosure::do_thread(Thread *target) {1671JavaThread *jt = target->as_Java_thread();1672if (!jt->is_exiting() && jt->threadObj() != NULL) {1673_result = ((JvmtiEnvBase *)_env)->get_stack_trace(jt,1674_start_depth, _max_count,1675_frame_buffer, _count_ptr);1676}1677}16781679void1680GetFrameCountClosure::do_thread(Thread *target) {1681JavaThread* jt = _state->get_thread();1682assert(target == jt, "just checking");1683if (!jt->is_exiting() && jt->threadObj() != NULL) {1684_result = ((JvmtiEnvBase*)_env)->get_frame_count(_state, _count_ptr);1685}1686}16871688void1689GetFrameLocationClosure::do_thread(Thread *target) {1690JavaThread *jt = target->as_Java_thread();1691if (!jt->is_exiting() && jt->threadObj() != NULL) {1692_result = ((JvmtiEnvBase*)_env)->get_frame_location(jt, _depth,1693_method_ptr, _location_ptr);1694}1695}169616971698