src/share/vm/prims/jvmtiEnvBase.cpp

Fri, 10 Jul 2009 11:10:00 -0700

author
mchung
date
Fri, 10 Jul 2009 11:10:00 -0700
changeset 1310
6a93908f268f
parent 1046
2f716c0acb64
child 1253
b109e761e927
permissions
-rw-r--r--

6857194: Add hotspot perf counters to aid class loading performance measurement
Summary: Add new jvmstat counters to measure detailed class loading time
Reviewed-by: acorn, kamg

     1 /*
     2  * Copyright 2003-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    24 # include "incls/_precompiled.incl"
    25 # include "incls/_jvmtiEnvBase.cpp.incl"
    28 ///////////////////////////////////////////////////////////////
    29 //
    30 // JvmtiEnvBase
    31 //
    33 JvmtiEnvBase* JvmtiEnvBase::_head_environment = NULL;
    35 bool JvmtiEnvBase::_globally_initialized = false;
    36 volatile bool JvmtiEnvBase::_needs_clean_up = false;
    38 jvmtiPhase JvmtiEnvBase::_phase = JVMTI_PHASE_PRIMORDIAL;
    40 volatile int JvmtiEnvBase::_dying_thread_env_iteration_count = 0;
    42 extern jvmtiInterface_1_ jvmti_Interface;
    43 extern jvmtiInterface_1_ jvmtiTrace_Interface;
    46 // perform initializations that must occur before any JVMTI environments
    47 // are released but which should only be initialized once (no matter
    48 // how many environments are created).
    49 void
    50 JvmtiEnvBase::globally_initialize() {
    51   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
    52   assert(_globally_initialized == false, "bad call");
    54   JvmtiManageCapabilities::initialize();
    56 #ifndef JVMTI_KERNEL
    57   // register extension functions and events
    58   JvmtiExtensions::register_extensions();
    59 #endif // !JVMTI_KERNEL
    61 #ifdef JVMTI_TRACE
    62   JvmtiTrace::initialize();
    63 #endif
    65   _globally_initialized = true;
    66 }
    69 void
    70 JvmtiEnvBase::initialize() {
    71   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
    73   // Add this environment to the end of the environment list (order is important)
    74   {
    75     // This block of code must not contain any safepoints, as list deallocation
    76     // (which occurs at a safepoint) cannot occur simultaneously with this list
    77     // addition.  Note: No_Safepoint_Verifier cannot, currently, be used before
    78     // threads exist.
    79     JvmtiEnvIterator it;
    80     JvmtiEnvBase *previous_env = NULL;
    81     for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
    82       previous_env = env;
    83     }
    84     if (previous_env == NULL) {
    85       _head_environment = this;
    86     } else {
    87       previous_env->set_next_environment(this);
    88     }
    89   }
    91   if (_globally_initialized == false) {
    92     globally_initialize();
    93   }
    94 }
    97 bool
    98 JvmtiEnvBase::is_valid() {
    99   jint value = 0;
   101   // This object might not be a JvmtiEnvBase so we can't assume
   102   // the _magic field is properly aligned. Get the value in a safe
   103   // way and then check against JVMTI_MAGIC.
   105   switch (sizeof(_magic)) {
   106   case 2:
   107     value = Bytes::get_native_u2((address)&_magic);
   108     break;
   110   case 4:
   111     value = Bytes::get_native_u4((address)&_magic);
   112     break;
   114   case 8:
   115     value = Bytes::get_native_u8((address)&_magic);
   116     break;
   118   default:
   119     guarantee(false, "_magic field is an unexpected size");
   120   }
   122   return value == JVMTI_MAGIC;
   123 }
   126 JvmtiEnvBase::JvmtiEnvBase() : _env_event_enable() {
   127   _env_local_storage = NULL;
   128   _tag_map = NULL;
   129   _native_method_prefix_count = 0;
   130   _native_method_prefixes = NULL;
   131   _next = NULL;
   132   _class_file_load_hook_ever_enabled = false;
   134   // Moot since ClassFileLoadHook not yet enabled.
   135   // But "true" will give a more predictable ClassFileLoadHook behavior
   136   // for environment creation during ClassFileLoadHook.
   137   _is_retransformable = true;
   139   // all callbacks initially NULL
   140   memset(&_event_callbacks,0,sizeof(jvmtiEventCallbacks));
   142   // all capabilities initially off
   143   memset(&_current_capabilities, 0, sizeof(_current_capabilities));
   145   // all prohibited capabilities initially off
   146   memset(&_prohibited_capabilities, 0, sizeof(_prohibited_capabilities));
   148   _magic = JVMTI_MAGIC;
   150   JvmtiEventController::env_initialize((JvmtiEnv*)this);
   152 #ifdef JVMTI_TRACE
   153   _jvmti_external.functions = TraceJVMTI != NULL ? &jvmtiTrace_Interface : &jvmti_Interface;
   154 #else
   155   _jvmti_external.functions = &jvmti_Interface;
   156 #endif
   157 }
   160 void
   161 JvmtiEnvBase::dispose() {
   163 #ifdef JVMTI_TRACE
   164   JvmtiTrace::shutdown();
   165 #endif
   167   // Dispose of event info and let the event controller call us back
   168   // in a locked state (env_dispose, below)
   169   JvmtiEventController::env_dispose(this);
   170 }
   172 void
   173 JvmtiEnvBase::env_dispose() {
   174   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
   176   // We have been entered with all events disabled on this environment.
   177   // A race to re-enable events (by setting callbacks) is prevented by
   178   // checking for a valid environment when setting callbacks (while
   179   // holding the JvmtiThreadState_lock).
   181   // Mark as invalid.
   182   _magic = DISPOSED_MAGIC;
   184   // Relinquish all capabilities.
   185   jvmtiCapabilities *caps = get_capabilities();
   186   JvmtiManageCapabilities::relinquish_capabilities(caps, caps, caps);
   188   // Same situation as with events (see above)
   189   set_native_method_prefixes(0, NULL);
   191 #ifndef JVMTI_KERNEL
   192   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
   193   set_tag_map(NULL);
   194   // A tag map can be big, deallocate it now
   195   if (tag_map_to_deallocate != NULL) {
   196     delete tag_map_to_deallocate;
   197   }
   198 #endif // !JVMTI_KERNEL
   200   _needs_clean_up = true;
   201 }
   204 JvmtiEnvBase::~JvmtiEnvBase() {
   205   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
   207   // There is a small window of time during which the tag map of a
   208   // disposed environment could have been reallocated.
   209   // Make sure it is gone.
   210 #ifndef JVMTI_KERNEL
   211   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
   212   set_tag_map(NULL);
   213   // A tag map can be big, deallocate it now
   214   if (tag_map_to_deallocate != NULL) {
   215     delete tag_map_to_deallocate;
   216   }
   217 #endif // !JVMTI_KERNEL
   219   _magic = BAD_MAGIC;
   220 }
   223 void
   224 JvmtiEnvBase::periodic_clean_up() {
   225   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
   227   // JvmtiEnvBase reference is saved in JvmtiEnvThreadState. So
   228   // clean up JvmtiThreadState before deleting JvmtiEnv pointer.
   229   JvmtiThreadState::periodic_clean_up();
   231   // Unlink all invalid environments from the list of environments
   232   // and deallocate them
   233   JvmtiEnvIterator it;
   234   JvmtiEnvBase* previous_env = NULL;
   235   JvmtiEnvBase* env = it.first();
   236   while (env != NULL) {
   237     if (env->is_valid()) {
   238       previous_env = env;
   239       env = it.next(env);
   240     } else {
   241       // This one isn't valid, remove it from the list and deallocate it
   242       JvmtiEnvBase* defunct_env = env;
   243       env = it.next(env);
   244       if (previous_env == NULL) {
   245         _head_environment = env;
   246       } else {
   247         previous_env->set_next_environment(env);
   248       }
   249       delete defunct_env;
   250     }
   251   }
   253 }
   256 void
   257 JvmtiEnvBase::check_for_periodic_clean_up() {
   258   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
   260   class ThreadInsideIterationClosure: public ThreadClosure {
   261    private:
   262     bool _inside;
   263    public:
   264     ThreadInsideIterationClosure() : _inside(false) {};
   266     void do_thread(Thread* thread) {
   267       _inside |= thread->is_inside_jvmti_env_iteration();
   268     }
   270     bool is_inside_jvmti_env_iteration() {
   271       return _inside;
   272     }
   273   };
   275   if (_needs_clean_up) {
   276     // Check if we are currently iterating environment,
   277     // deallocation should not occur if we are
   278     ThreadInsideIterationClosure tiic;
   279     Threads::threads_do(&tiic);
   280     if (!tiic.is_inside_jvmti_env_iteration() &&
   281              !is_inside_dying_thread_env_iteration()) {
   282       _needs_clean_up = false;
   283       JvmtiEnvBase::periodic_clean_up();
   284     }
   285   }
   286 }
   289 void
   290 JvmtiEnvBase::record_first_time_class_file_load_hook_enabled() {
   291   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
   292          "sanity check");
   294   if (!_class_file_load_hook_ever_enabled) {
   295     _class_file_load_hook_ever_enabled = true;
   297     if (get_capabilities()->can_retransform_classes) {
   298       _is_retransformable = true;
   299     } else {
   300       _is_retransformable = false;
   302       // cannot add retransform capability after ClassFileLoadHook has been enabled
   303       get_prohibited_capabilities()->can_retransform_classes = 1;
   304     }
   305   }
   306 }
   309 void
   310 JvmtiEnvBase::record_class_file_load_hook_enabled() {
   311   if (!_class_file_load_hook_ever_enabled) {
   312     if (Threads::number_of_threads() == 0) {
   313       record_first_time_class_file_load_hook_enabled();
   314     } else {
   315       MutexLocker mu(JvmtiThreadState_lock);
   316       record_first_time_class_file_load_hook_enabled();
   317     }
   318   }
   319 }
   322 jvmtiError
   323 JvmtiEnvBase::set_native_method_prefixes(jint prefix_count, char** prefixes) {
   324   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
   325          "sanity check");
   327   int old_prefix_count = get_native_method_prefix_count();
   328   char **old_prefixes = get_native_method_prefixes();
   330   // allocate and install the new prefixex
   331   if (prefix_count == 0 || !is_valid()) {
   332     _native_method_prefix_count = 0;
   333     _native_method_prefixes = NULL;
   334   } else {
   335     // there are prefixes, allocate an array to hold them, and fill it
   336     char** new_prefixes = (char**)os::malloc((prefix_count) * sizeof(char*));
   337     if (new_prefixes == NULL) {
   338       return JVMTI_ERROR_OUT_OF_MEMORY;
   339     }
   340     for (int i = 0; i < prefix_count; i++) {
   341       char* prefix = prefixes[i];
   342       if (prefix == NULL) {
   343         for (int j = 0; j < (i-1); j++) {
   344           os::free(new_prefixes[j]);
   345         }
   346         os::free(new_prefixes);
   347         return JVMTI_ERROR_NULL_POINTER;
   348       }
   349       prefix = os::strdup(prefixes[i]);
   350       if (prefix == NULL) {
   351         for (int j = 0; j < (i-1); j++) {
   352           os::free(new_prefixes[j]);
   353         }
   354         os::free(new_prefixes);
   355         return JVMTI_ERROR_OUT_OF_MEMORY;
   356       }
   357       new_prefixes[i] = prefix;
   358     }
   359     _native_method_prefix_count = prefix_count;
   360     _native_method_prefixes = new_prefixes;
   361   }
   363   // now that we know the new prefixes have been successfully installed we can
   364   // safely remove the old ones
   365   if (old_prefix_count != 0) {
   366     for (int i = 0; i < old_prefix_count; i++) {
   367       os::free(old_prefixes[i]);
   368     }
   369     os::free(old_prefixes);
   370   }
   372   return JVMTI_ERROR_NONE;
   373 }
   376 // Collect all the prefixes which have been set in any JVM TI environments
   377 // by the SetNativeMethodPrefix(es) functions.  Be sure to maintain the
   378 // order of environments and the order of prefixes within each environment.
   379 // Return in a resource allocated array.
   380 char**
   381 JvmtiEnvBase::get_all_native_method_prefixes(int* count_ptr) {
   382   assert(Threads::number_of_threads() == 0 ||
   383          SafepointSynchronize::is_at_safepoint() ||
   384          JvmtiThreadState_lock->is_locked(),
   385          "sanity check");
   387   int total_count = 0;
   388   GrowableArray<char*>* prefix_array =new GrowableArray<char*>(5);
   390   JvmtiEnvIterator it;
   391   for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
   392     int prefix_count = env->get_native_method_prefix_count();
   393     char** prefixes = env->get_native_method_prefixes();
   394     for (int j = 0; j < prefix_count; j++) {
   395       // retrieve a prefix and so that it is safe against asynchronous changes
   396       // copy it into the resource area
   397       char* prefix = prefixes[j];
   398       char* prefix_copy = NEW_RESOURCE_ARRAY(char, strlen(prefix)+1);
   399       strcpy(prefix_copy, prefix);
   400       prefix_array->at_put_grow(total_count++, prefix_copy);
   401     }
   402   }
   404   char** all_prefixes = NEW_RESOURCE_ARRAY(char*, total_count);
   405   char** p = all_prefixes;
   406   for (int i = 0; i < total_count; ++i) {
   407     *p++ = prefix_array->at(i);
   408   }
   409   *count_ptr = total_count;
   410   return all_prefixes;
   411 }
   413 void
   414 JvmtiEnvBase::set_event_callbacks(const jvmtiEventCallbacks* callbacks,
   415                                                jint size_of_callbacks) {
   416   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
   418   size_t byte_cnt = sizeof(jvmtiEventCallbacks);
   420   // clear in either case to be sure we got any gap between sizes
   421   memset(&_event_callbacks, 0, byte_cnt);
   423   // Now that JvmtiThreadState_lock is held, prevent a possible race condition where events
   424   // are re-enabled by a call to set event callbacks where the DisposeEnvironment
   425   // occurs after the boiler-plate environment check and before the lock is acquired.
   426   if (callbacks != NULL && is_valid()) {
   427     if (size_of_callbacks < (jint)byte_cnt) {
   428       byte_cnt = size_of_callbacks;
   429     }
   430     memcpy(&_event_callbacks, callbacks, byte_cnt);
   431   }
   432 }
   434 // Called from JVMTI entry points which perform stack walking. If the
   435 // associated JavaThread is the current thread, then wait_for_suspend
   436 // is not used. Otherwise, it determines if we should wait for the
   437 // "other" thread to complete external suspension. (NOTE: in future
   438 // releases the suspension mechanism should be reimplemented so this
   439 // is not necessary.)
   440 //
   441 bool
   442 JvmtiEnvBase::is_thread_fully_suspended(JavaThread* thr, bool wait_for_suspend, uint32_t *bits) {
   443   // "other" threads require special handling
   444   if (thr != JavaThread::current()) {
   445     if (wait_for_suspend) {
   446       // We are allowed to wait for the external suspend to complete
   447       // so give the other thread a chance to get suspended.
   448       if (!thr->wait_for_ext_suspend_completion(SuspendRetryCount,
   449           SuspendRetryDelay, bits)) {
   450         // didn't make it so let the caller know
   451         return false;
   452       }
   453     }
   454     // We aren't allowed to wait for the external suspend to complete
   455     // so if the other thread isn't externally suspended we need to
   456     // let the caller know.
   457     else if (!thr->is_ext_suspend_completed_with_lock(bits)) {
   458       return false;
   459     }
   460   }
   462   return true;
   463 }
   466 // In the fullness of time, all users of the method should instead
   467 // directly use allocate, besides being cleaner and faster, this will
   468 // mean much better out of memory handling
   469 unsigned char *
   470 JvmtiEnvBase::jvmtiMalloc(jlong size) {
   471   unsigned char* mem;
   472   jvmtiError result = allocate(size, &mem);
   473   assert(result == JVMTI_ERROR_NONE, "Allocate failed");
   474   return mem;
   475 }
   478 //
   479 // Threads
   480 //
   482 jobject *
   483 JvmtiEnvBase::new_jobjectArray(int length, Handle *handles) {
   484   if (length == 0) {
   485     return NULL;
   486   }
   488   jobject *objArray = (jobject *) jvmtiMalloc(sizeof(jobject) * length);
   489   NULL_CHECK(objArray, NULL);
   491   for (int i=0; i<length; i++) {
   492     objArray[i] = jni_reference(handles[i]);
   493   }
   494   return objArray;
   495 }
   497 jthread *
   498 JvmtiEnvBase::new_jthreadArray(int length, Handle *handles) {
   499   return (jthread *) new_jobjectArray(length,handles);
   500 }
   502 jthreadGroup *
   503 JvmtiEnvBase::new_jthreadGroupArray(int length, Handle *handles) {
   504   return (jthreadGroup *) new_jobjectArray(length,handles);
   505 }
   508 JavaThread *
   509 JvmtiEnvBase::get_JavaThread(jthread jni_thread) {
   510   oop t = JNIHandles::resolve_external_guard(jni_thread);
   511   if (t == NULL || !t->is_a(SystemDictionary::thread_klass())) {
   512     return NULL;
   513   }
   514   // The following returns NULL if the thread has not yet run or is in
   515   // process of exiting
   516   return java_lang_Thread::thread(t);
   517 }
   520 // update the access_flags for the field in the klass
   521 void
   522 JvmtiEnvBase::update_klass_field_access_flag(fieldDescriptor *fd) {
   523   instanceKlass* ik = instanceKlass::cast(fd->field_holder());
   524   typeArrayOop fields = ik->fields();
   525   fields->ushort_at_put(fd->index(), (jushort)fd->access_flags().as_short());
   526 }
   529 // return the vframe on the specified thread and depth, NULL if no such frame
   530 vframe*
   531 JvmtiEnvBase::vframeFor(JavaThread* java_thread, jint depth) {
   532   if (!java_thread->has_last_Java_frame()) {
   533     return NULL;
   534   }
   535   RegisterMap reg_map(java_thread);
   536   vframe *vf = java_thread->last_java_vframe(&reg_map);
   537   int d = 0;
   538   while ((vf != NULL) && (d < depth)) {
   539     vf = vf->java_sender();
   540     d++;
   541   }
   542   return vf;
   543 }
   546 //
   547 // utilities: JNI objects
   548 //
   551 jclass
   552 JvmtiEnvBase::get_jni_class_non_null(klassOop k) {
   553   assert(k != NULL, "k != NULL");
   554   return (jclass)jni_reference(Klass::cast(k)->java_mirror());
   555 }
   557 #ifndef JVMTI_KERNEL
   559 //
   560 // Field Information
   561 //
   563 bool
   564 JvmtiEnvBase::get_field_descriptor(klassOop k, jfieldID field, fieldDescriptor* fd) {
   565   if (!jfieldIDWorkaround::is_valid_jfieldID(k, field)) {
   566     return false;
   567   }
   568   bool found = false;
   569   if (jfieldIDWorkaround::is_static_jfieldID(field)) {
   570     JNIid* id = jfieldIDWorkaround::from_static_jfieldID(field);
   571     int offset = id->offset();
   572     klassOop holder = id->holder();
   573     found = instanceKlass::cast(holder)->find_local_field_from_offset(offset, true, fd);
   574   } else {
   575     // Non-static field. The fieldID is really the offset of the field within the object.
   576     int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);
   577     found = instanceKlass::cast(k)->find_field_from_offset(offset, false, fd);
   578   }
   579   return found;
   580 }
   582 //
   583 // Object Monitor Information
   584 //
   586 //
   587 // Count the number of objects for a lightweight monitor. The hobj
   588 // parameter is object that owns the monitor so this routine will
   589 // count the number of times the same object was locked by frames
   590 // in java_thread.
   591 //
   592 jint
   593 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
   594   jint ret = 0;
   595   if (!java_thread->has_last_Java_frame()) {
   596     return ret;  // no Java frames so no monitors
   597   }
   599   ResourceMark rm;
   600   HandleMark   hm;
   601   RegisterMap  reg_map(java_thread);
   603   for(javaVFrame *jvf=java_thread->last_java_vframe(&reg_map); jvf != NULL;
   604                                                  jvf = jvf->java_sender()) {
   605     GrowableArray<MonitorInfo*>* mons = jvf->monitors();
   606     if (!mons->is_empty()) {
   607       for (int i = 0; i < mons->length(); i++) {
   608         MonitorInfo *mi = mons->at(i);
   610         // see if owner of the monitor is our object
   611         if (mi->owner() != NULL && mi->owner() == hobj()) {
   612           ret++;
   613         }
   614       }
   615     }
   616   }
   617   return ret;
   618 }
   622 jvmtiError
   623 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread, jobject *monitor_ptr) {
   624 #ifdef ASSERT
   625   uint32_t debug_bits = 0;
   626 #endif
   627   assert((SafepointSynchronize::is_at_safepoint() ||
   628           is_thread_fully_suspended(java_thread, false, &debug_bits)),
   629          "at safepoint or target thread is suspended");
   630   oop obj = NULL;
   631   ObjectMonitor *mon = java_thread->current_waiting_monitor();
   632   if (mon == NULL) {
   633     // thread is not doing an Object.wait() call
   634     mon = java_thread->current_pending_monitor();
   635     if (mon != NULL) {
   636       // The thread is trying to enter() or raw_enter() an ObjectMonitor.
   637       obj = (oop)mon->object();
   638       // If obj == NULL, then ObjectMonitor is raw which doesn't count
   639       // as contended for this API
   640     }
   641     // implied else: no contended ObjectMonitor
   642   } else {
   643     // thread is doing an Object.wait() call
   644     obj = (oop)mon->object();
   645     assert(obj != NULL, "Object.wait() should have an object");
   646   }
   648   if (obj == NULL) {
   649     *monitor_ptr = NULL;
   650   } else {
   651     HandleMark hm;
   652     Handle     hobj(obj);
   653     *monitor_ptr = jni_reference(calling_thread, hobj);
   654   }
   655   return JVMTI_ERROR_NONE;
   656 }
   659 jvmtiError
   660 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
   661                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
   662   jvmtiError err = JVMTI_ERROR_NONE;
   663 #ifdef ASSERT
   664   uint32_t debug_bits = 0;
   665 #endif
   666   assert((SafepointSynchronize::is_at_safepoint() ||
   667           is_thread_fully_suspended(java_thread, false, &debug_bits)),
   668          "at safepoint or target thread is suspended");
   670   if (java_thread->has_last_Java_frame()) {
   671     ResourceMark rm;
   672     HandleMark   hm;
   673     RegisterMap  reg_map(java_thread);
   675     int depth = 0;
   676     for (javaVFrame *jvf = java_thread->last_java_vframe(&reg_map); jvf != NULL;
   677          jvf = jvf->java_sender()) {
   678       if (depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
   679         // add locked objects for this frame into list
   680         err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
   681         if (err != JVMTI_ERROR_NONE) {
   682           return err;
   683         }
   684       }
   685     }
   686   }
   688   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
   689   JvmtiMonitorClosure jmc(java_thread, calling_thread, owned_monitors_list, this);
   690   ObjectSynchronizer::monitors_iterate(&jmc);
   691   err = jmc.error();
   693   return err;
   694 }
   696 // Save JNI local handles for any objects that this frame owns.
   697 jvmtiError
   698 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
   699                                  javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, int stack_depth) {
   700   jvmtiError err = JVMTI_ERROR_NONE;
   701   ResourceMark rm;
   703   GrowableArray<MonitorInfo*>* mons = jvf->monitors();
   704   if (mons->is_empty()) {
   705     return err;  // this javaVFrame holds no monitors
   706   }
   708   HandleMark hm;
   709   oop wait_obj = NULL;
   710   {
   711     // save object of current wait() call (if any) for later comparison
   712     ObjectMonitor *mon = java_thread->current_waiting_monitor();
   713     if (mon != NULL) {
   714       wait_obj = (oop)mon->object();
   715     }
   716   }
   717   oop pending_obj = NULL;
   718   {
   719     // save object of current enter() call (if any) for later comparison
   720     ObjectMonitor *mon = java_thread->current_pending_monitor();
   721     if (mon != NULL) {
   722       pending_obj = (oop)mon->object();
   723     }
   724   }
   726   for (int i = 0; i < mons->length(); i++) {
   727     MonitorInfo *mi = mons->at(i);
   729     oop obj = mi->owner();
   730     if (obj == NULL) {
   731       // this monitor doesn't have an owning object so skip it
   732       continue;
   733     }
   735     if (wait_obj == obj) {
   736       // the thread is waiting on this monitor so it isn't really owned
   737       continue;
   738     }
   740     if (pending_obj == obj) {
   741       // the thread is pending on this monitor so it isn't really owned
   742       continue;
   743     }
   745     if (owned_monitors_list->length() > 0) {
   746       // Our list has at least one object on it so we have to check
   747       // for recursive object locking
   748       bool found = false;
   749       for (int j = 0; j < owned_monitors_list->length(); j++) {
   750         jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
   751         oop check = JNIHandles::resolve(jobj);
   752         if (check == obj) {
   753           found = true;  // we found the object
   754           break;
   755         }
   756       }
   758       if (found) {
   759         // already have this object so don't include it
   760         continue;
   761       }
   762     }
   764     // add the owning object to our list
   765     jvmtiMonitorStackDepthInfo *jmsdi;
   766     err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
   767     if (err != JVMTI_ERROR_NONE) {
   768         return err;
   769     }
   770     Handle hobj(obj);
   771     jmsdi->monitor = jni_reference(calling_thread, hobj);
   772     jmsdi->stack_depth = stack_depth;
   773     owned_monitors_list->append(jmsdi);
   774   }
   776   return err;
   777 }
   779 jvmtiError
   780 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
   781                               jint start_depth, jint max_count,
   782                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
   783 #ifdef ASSERT
   784   uint32_t debug_bits = 0;
   785 #endif
   786   assert((SafepointSynchronize::is_at_safepoint() ||
   787           is_thread_fully_suspended(java_thread, false, &debug_bits)),
   788          "at safepoint or target thread is suspended");
   789   int count = 0;
   790   if (java_thread->has_last_Java_frame()) {
   791     RegisterMap reg_map(java_thread);
   792     Thread* current_thread = Thread::current();
   793     ResourceMark rm(current_thread);
   794     javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
   795     HandleMark hm(current_thread);
   796     if (start_depth != 0) {
   797       if (start_depth > 0) {
   798         for (int j = 0; j < start_depth && jvf != NULL; j++) {
   799           jvf = jvf->java_sender();
   800         }
   801         if (jvf == NULL) {
   802           // start_depth is deeper than the stack depth
   803           return JVMTI_ERROR_ILLEGAL_ARGUMENT;
   804         }
   805       } else { // start_depth < 0
   806         // we are referencing the starting depth based on the oldest
   807         // part of the stack.
   808         // optimize to limit the number of times that java_sender() is called
   809         javaVFrame *jvf_cursor = jvf;
   810         javaVFrame *jvf_prev = NULL;
   811         javaVFrame *jvf_prev_prev;
   812         int j = 0;
   813         while (jvf_cursor != NULL) {
   814           jvf_prev_prev = jvf_prev;
   815           jvf_prev = jvf_cursor;
   816           for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
   817             jvf_cursor = jvf_cursor->java_sender();
   818           }
   819         }
   820         if (j == start_depth) {
   821           // previous pointer is exactly where we want to start
   822           jvf = jvf_prev;
   823         } else {
   824           // we need to back up further to get to the right place
   825           if (jvf_prev_prev == NULL) {
   826             // the -start_depth is greater than the stack depth
   827             return JVMTI_ERROR_ILLEGAL_ARGUMENT;
   828           }
   829           // j now is the number of frames on the stack starting with
   830           // jvf_prev, we start from jvf_prev_prev and move older on
   831           // the stack that many, the result is -start_depth frames
   832           // remaining.
   833           jvf = jvf_prev_prev;
   834           for (; j < 0; j++) {
   835             jvf = jvf->java_sender();
   836           }
   837         }
   838       }
   839     }
   840     for (; count < max_count && jvf != NULL; count++) {
   841       frame_buffer[count].method = jvf->method()->jmethod_id();
   842       frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
   843       jvf = jvf->java_sender();
   844     }
   845   } else {
   846     if (start_depth != 0) {
   847       // no frames and there is a starting depth
   848       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
   849     }
   850   }
   851   *count_ptr = count;
   852   return JVMTI_ERROR_NONE;
   853 }
   855 jvmtiError
   856 JvmtiEnvBase::get_frame_count(JvmtiThreadState *state, jint *count_ptr) {
   857   assert((state != NULL),
   858          "JavaThread should create JvmtiThreadState before calling this method");
   859   *count_ptr = state->count_frames();
   860   return JVMTI_ERROR_NONE;
   861 }
   863 jvmtiError
   864 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
   865                                  jmethodID* method_ptr, jlocation* location_ptr) {
   866 #ifdef ASSERT
   867   uint32_t debug_bits = 0;
   868 #endif
   869   assert((SafepointSynchronize::is_at_safepoint() ||
   870           is_thread_fully_suspended(java_thread, false, &debug_bits)),
   871          "at safepoint or target thread is suspended");
   872   Thread* current_thread = Thread::current();
   873   ResourceMark rm(current_thread);
   875   vframe *vf = vframeFor(java_thread, depth);
   876   if (vf == NULL) {
   877     return JVMTI_ERROR_NO_MORE_FRAMES;
   878   }
   880   // vframeFor should return a java frame. If it doesn't
   881   // it means we've got an internal error and we return the
   882   // error in product mode. In debug mode we will instead
   883   // attempt to cast the vframe to a javaVFrame and will
   884   // cause an assertion/crash to allow further diagnosis.
   885 #ifdef PRODUCT
   886   if (!vf->is_java_frame()) {
   887     return JVMTI_ERROR_INTERNAL;
   888   }
   889 #endif
   891   HandleMark hm(current_thread);
   892   javaVFrame *jvf = javaVFrame::cast(vf);
   893   methodOop method = jvf->method();
   894   if (method->is_native()) {
   895     *location_ptr = -1;
   896   } else {
   897     *location_ptr = jvf->bci();
   898   }
   899   *method_ptr = method->jmethod_id();
   901   return JVMTI_ERROR_NONE;
   902 }
   905 jvmtiError
   906 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
   907   HandleMark hm;
   908   Handle hobj;
   910   bool at_safepoint = SafepointSynchronize::is_at_safepoint();
   912   // Check arguments
   913   {
   914     oop mirror = JNIHandles::resolve_external_guard(object);
   915     NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
   916     NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
   918     hobj = Handle(mirror);
   919   }
   921   JavaThread *owning_thread = NULL;
   922   ObjectMonitor *mon = NULL;
   923   jvmtiMonitorUsage ret = {
   924       NULL, 0, 0, NULL, 0, NULL
   925   };
   927   uint32_t debug_bits = 0;
   928   // first derive the object's owner and entry_count (if any)
   929   {
   930     // Revoke any biases before querying the mark word
   931     if (SafepointSynchronize::is_at_safepoint()) {
   932       BiasedLocking::revoke_at_safepoint(hobj);
   933     } else {
   934       BiasedLocking::revoke_and_rebias(hobj, false, calling_thread);
   935     }
   937     address owner = NULL;
   938     {
   939       markOop mark = hobj()->mark();
   941       if (!mark->has_monitor()) {
   942         // this object has a lightweight monitor
   944         if (mark->has_locker()) {
   945           owner = (address)mark->locker(); // save the address of the Lock word
   946         }
   947         // implied else: no owner
   948       } else {
   949         // this object has a heavyweight monitor
   950         mon = mark->monitor();
   952         // The owner field of a heavyweight monitor may be NULL for no
   953         // owner, a JavaThread * or it may still be the address of the
   954         // Lock word in a JavaThread's stack. A monitor can be inflated
   955         // by a non-owning JavaThread, but only the owning JavaThread
   956         // can change the owner field from the Lock word to the
   957         // JavaThread * and it may not have done that yet.
   958         owner = (address)mon->owner();
   959       }
   960     }
   962     if (owner != NULL) {
   963       // This monitor is owned so we have to find the owning JavaThread.
   964       // Since owning_thread_from_monitor_owner() grabs a lock, GC can
   965       // move our object at this point. However, our owner value is safe
   966       // since it is either the Lock word on a stack or a JavaThread *.
   967       owning_thread = Threads::owning_thread_from_monitor_owner(owner, !at_safepoint);
   968       assert(owning_thread != NULL, "sanity check");
   969       if (owning_thread != NULL) {  // robustness
   970         // The monitor's owner either has to be the current thread, at safepoint
   971         // or it has to be suspended. Any of these conditions will prevent both
   972         // contending and waiting threads from modifying the state of
   973         // the monitor.
   974         if (!at_safepoint && !JvmtiEnv::is_thread_fully_suspended(owning_thread, true, &debug_bits)) {
   975           return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
   976         }
   977         HandleMark hm;
   978         Handle     th(owning_thread->threadObj());
   979         ret.owner = (jthread)jni_reference(calling_thread, th);
   980       }
   981       // implied else: no owner
   982     }
   984     if (owning_thread != NULL) {  // monitor is owned
   985       if ((address)owning_thread == owner) {
   986         // the owner field is the JavaThread *
   987         assert(mon != NULL,
   988           "must have heavyweight monitor with JavaThread * owner");
   989         ret.entry_count = mon->recursions() + 1;
   990       } else {
   991         // The owner field is the Lock word on the JavaThread's stack
   992         // so the recursions field is not valid. We have to count the
   993         // number of recursive monitor entries the hard way. We pass
   994         // a handle to survive any GCs along the way.
   995         ResourceMark rm;
   996         ret.entry_count = count_locked_objects(owning_thread, hobj);
   997       }
   998     }
   999     // implied else: entry_count == 0
  1002   int nWant,nWait;
  1003   if (mon != NULL) {
  1004     // this object has a heavyweight monitor
  1005     nWant = mon->contentions(); // # of threads contending for monitor
  1006     nWait = mon->waiters();     // # of threads in Object.wait()
  1007     ret.waiter_count = nWant + nWait;
  1008     ret.notify_waiter_count = nWait;
  1009   } else {
  1010     // this object has a lightweight monitor
  1011     ret.waiter_count = 0;
  1012     ret.notify_waiter_count = 0;
  1015   // Allocate memory for heavyweight and lightweight monitor.
  1016   jvmtiError err;
  1017   err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
  1018   if (err != JVMTI_ERROR_NONE) {
  1019     return err;
  1021   err = allocate(ret.notify_waiter_count * sizeof(jthread *),
  1022                  (unsigned char**)&ret.notify_waiters);
  1023   if (err != JVMTI_ERROR_NONE) {
  1024     deallocate((unsigned char*)ret.waiters);
  1025     return err;
  1028   // now derive the rest of the fields
  1029   if (mon != NULL) {
  1030     // this object has a heavyweight monitor
  1032     // Number of waiters may actually be less than the waiter count.
  1033     // So NULL out memory so that unused memory will be NULL.
  1034     memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
  1035     memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
  1037     if (ret.waiter_count > 0) {
  1038       // we have contending and/or waiting threads
  1039       HandleMark hm;
  1040       if (nWant > 0) {
  1041         // we have contending threads
  1042         ResourceMark rm;
  1043         // get_pending_threads returns only java thread so we do not need to
  1044         // check for  non java threads.
  1045         GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(
  1046           nWant, (address)mon, !at_safepoint);
  1047         if (wantList->length() < nWant) {
  1048           // robustness: the pending list has gotten smaller
  1049           nWant = wantList->length();
  1051         for (int i = 0; i < nWant; i++) {
  1052           JavaThread *pending_thread = wantList->at(i);
  1053           // If the monitor has no owner, then a non-suspended contending
  1054           // thread could potentially change the state of the monitor by
  1055           // entering it. The JVM/TI spec doesn't allow this.
  1056           if (owning_thread == NULL && !at_safepoint &
  1057               !JvmtiEnv::is_thread_fully_suspended(pending_thread, true, &debug_bits)) {
  1058             if (ret.owner != NULL) {
  1059               destroy_jni_reference(calling_thread, ret.owner);
  1061             for (int j = 0; j < i; j++) {
  1062               destroy_jni_reference(calling_thread, ret.waiters[j]);
  1064             deallocate((unsigned char*)ret.waiters);
  1065             deallocate((unsigned char*)ret.notify_waiters);
  1066             return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
  1068           Handle th(pending_thread->threadObj());
  1069           ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
  1072       if (nWait > 0) {
  1073         // we have threads in Object.wait()
  1074         int offset = nWant;  // add after any contending threads
  1075         ObjectWaiter *waiter = mon->first_waiter();
  1076         for (int i = 0, j = 0; i < nWait; i++) {
  1077           if (waiter == NULL) {
  1078             // robustness: the waiting list has gotten smaller
  1079             nWait = j;
  1080             break;
  1082           Thread *t = mon->thread_of_waiter(waiter);
  1083           if (t != NULL && t->is_Java_thread()) {
  1084             JavaThread *wjava_thread = (JavaThread *)t;
  1085             // If the thread was found on the ObjectWaiter list, then
  1086             // it has not been notified. This thread can't change the
  1087             // state of the monitor so it doesn't need to be suspended.
  1088             Handle th(wjava_thread->threadObj());
  1089             ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
  1090             ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
  1092           waiter = mon->next_waiter(waiter);
  1097     // Adjust count. nWant and nWait count values may be less than original.
  1098     ret.waiter_count = nWant + nWait;
  1099     ret.notify_waiter_count = nWait;
  1100   } else {
  1101     // this object has a lightweight monitor and we have nothing more
  1102     // to do here because the defaults are just fine.
  1105   // we don't update return parameter unless everything worked
  1106   *info_ptr = ret;
  1108   return JVMTI_ERROR_NONE;
  1111 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
  1112   _env = env;
  1113   _allocations = new (ResourceObj::C_HEAP) GrowableArray<unsigned char*>(20, true);
  1114   _failed = false;
  1116 ResourceTracker::~ResourceTracker() {
  1117   if (_failed) {
  1118     for (int i=0; i<_allocations->length(); i++) {
  1119       _env->deallocate(_allocations->at(i));
  1122   delete _allocations;
  1125 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
  1126   unsigned char *ptr;
  1127   jvmtiError err = _env->allocate(size, &ptr);
  1128   if (err == JVMTI_ERROR_NONE) {
  1129     _allocations->append(ptr);
  1130     *mem_ptr = ptr;
  1131   } else {
  1132     *mem_ptr = NULL;
  1133     _failed = true;
  1135   return err;
  1138 unsigned char* ResourceTracker::allocate(jlong size) {
  1139   unsigned char* ptr;
  1140   allocate(size, &ptr);
  1141   return ptr;
  1144 char* ResourceTracker::strdup(const char* str) {
  1145   char *dup_str = (char*)allocate(strlen(str)+1);
  1146   if (dup_str != NULL) {
  1147     strcpy(dup_str, str);
  1149   return dup_str;
  1152 struct StackInfoNode {
  1153   struct StackInfoNode *next;
  1154   jvmtiStackInfo info;
  1155 };
  1157 // Create a jvmtiStackInfo inside a linked list node and create a
  1158 // buffer for the frame information, both allocated as resource objects.
  1159 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
  1160 // Note that either or both of thr and thread_oop
  1161 // may be null if the thread is new or has exited.
  1162 void
  1163 VM_GetMultipleStackTraces::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
  1164   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
  1166   jint state = 0;
  1167   struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
  1168   jvmtiStackInfo *infop = &(node->info);
  1169   node->next = head();
  1170   set_head(node);
  1171   infop->frame_count = 0;
  1172   infop->thread = jt;
  1174   if (thread_oop != NULL) {
  1175     // get most state bits
  1176     state = (jint)java_lang_Thread::get_thread_status(thread_oop);
  1179   if (thr != NULL) {    // add more state bits if there is a JavaThead to query
  1180     // same as is_being_ext_suspended() but without locking
  1181     if (thr->is_ext_suspended() || thr->is_external_suspend()) {
  1182       state |= JVMTI_THREAD_STATE_SUSPENDED;
  1184     JavaThreadState jts = thr->thread_state();
  1185     if (jts == _thread_in_native) {
  1186       state |= JVMTI_THREAD_STATE_IN_NATIVE;
  1188     OSThread* osThread = thr->osthread();
  1189     if (osThread != NULL && osThread->interrupted()) {
  1190       state |= JVMTI_THREAD_STATE_INTERRUPTED;
  1193   infop->state = state;
  1195   if (thr != NULL || (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
  1196     infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
  1197     env()->get_stack_trace(thr, 0, max_frame_count(),
  1198                            infop->frame_buffer, &(infop->frame_count));
  1199   } else {
  1200     infop->frame_buffer = NULL;
  1201     infop->frame_count = 0;
  1203   _frame_count_total += infop->frame_count;
  1206 // Based on the stack information in the linked list, allocate memory
  1207 // block to return and fill it from the info in the linked list.
  1208 void
  1209 VM_GetMultipleStackTraces::allocate_and_fill_stacks(jint thread_count) {
  1210   // do I need to worry about alignment issues?
  1211   jlong alloc_size =  thread_count       * sizeof(jvmtiStackInfo)
  1212                     + _frame_count_total * sizeof(jvmtiFrameInfo);
  1213   env()->allocate(alloc_size, (unsigned char **)&_stack_info);
  1215   // pointers to move through the newly allocated space as it is filled in
  1216   jvmtiStackInfo *si = _stack_info + thread_count;      // bottom of stack info
  1217   jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si;            // is the top of frame info
  1219   // copy information in resource area into allocated buffer
  1220   // insert stack info backwards since linked list is backwards
  1221   // insert frame info forwards
  1222   // walk the StackInfoNodes
  1223   for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {
  1224     jint frame_count = sin->info.frame_count;
  1225     size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
  1226     --si;
  1227     memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
  1228     if (frames_size == 0) {
  1229       si->frame_buffer = NULL;
  1230     } else {
  1231       memcpy(fi, sin->info.frame_buffer, frames_size);
  1232       si->frame_buffer = fi;  // point to the new allocated copy of the frames
  1233       fi += frame_count;
  1236   assert(si == _stack_info, "the last copied stack info must be the first record");
  1237   assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
  1238          "the last copied frame info must be the last record");
  1242 void
  1243 VM_GetThreadListStackTraces::doit() {
  1244   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
  1246   ResourceMark rm;
  1247   for (int i = 0; i < _thread_count; ++i) {
  1248     jthread jt = _thread_list[i];
  1249     oop thread_oop = JNIHandles::resolve_external_guard(jt);
  1250     if (thread_oop == NULL || !thread_oop->is_a(SystemDictionary::thread_klass())) {
  1251       set_result(JVMTI_ERROR_INVALID_THREAD);
  1252       return;
  1254     fill_frames(jt, java_lang_Thread::thread(thread_oop), thread_oop);
  1256   allocate_and_fill_stacks(_thread_count);
  1259 void
  1260 VM_GetAllStackTraces::doit() {
  1261   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
  1263   ResourceMark rm;
  1264   _final_thread_count = 0;
  1265   for (JavaThread *jt = Threads::first(); jt != NULL; jt = jt->next()) {
  1266     oop thread_oop = jt->threadObj();
  1267     if (thread_oop != NULL &&
  1268         !jt->is_exiting() &&
  1269         java_lang_Thread::is_alive(thread_oop) &&
  1270         !jt->is_hidden_from_external_view()) {
  1271       ++_final_thread_count;
  1272       // Handle block of the calling thread is used to create local refs.
  1273       fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
  1274                   jt, thread_oop);
  1277   allocate_and_fill_stacks(_final_thread_count);
  1280 // Verifies that the top frame is a java frame in an expected state.
  1281 // Deoptimizes frame if needed.
  1282 // Checks that the frame method signature matches the return type (tos).
  1283 // HandleMark must be defined in the caller only.
  1284 // It is to keep a ret_ob_h handle alive after return to the caller.
  1285 jvmtiError
  1286 JvmtiEnvBase::check_top_frame(JavaThread* current_thread, JavaThread* java_thread,
  1287                               jvalue value, TosState tos, Handle* ret_ob_h) {
  1288   ResourceMark rm(current_thread);
  1290   vframe *vf = vframeFor(java_thread, 0);
  1291   NULL_CHECK(vf, JVMTI_ERROR_NO_MORE_FRAMES);
  1293   javaVFrame *jvf = (javaVFrame*) vf;
  1294   if (!vf->is_java_frame() || jvf->method()->is_native()) {
  1295     return JVMTI_ERROR_OPAQUE_FRAME;
  1298   // If the frame is a compiled one, need to deoptimize it.
  1299   if (vf->is_compiled_frame()) {
  1300     if (!vf->fr().can_be_deoptimized()) {
  1301       return JVMTI_ERROR_OPAQUE_FRAME;
  1303     VM_DeoptimizeFrame deopt(java_thread, jvf->fr().id());
  1304     VMThread::execute(&deopt);
  1307   // Get information about method return type
  1308   symbolHandle signature(current_thread, jvf->method()->signature());
  1310   ResultTypeFinder rtf(signature);
  1311   TosState fr_tos = as_TosState(rtf.type());
  1312   if (fr_tos != tos) {
  1313     if (tos != itos || (fr_tos != btos && fr_tos != ctos && fr_tos != stos)) {
  1314       return JVMTI_ERROR_TYPE_MISMATCH;
  1318   // Check that the jobject class matches the return type signature.
  1319   jobject jobj = value.l;
  1320   if (tos == atos && jobj != NULL) { // NULL reference is allowed
  1321     Handle ob_h = Handle(current_thread, JNIHandles::resolve_external_guard(jobj));
  1322     NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
  1323     KlassHandle ob_kh = KlassHandle(current_thread, ob_h()->klass());
  1324     NULL_CHECK(ob_kh, JVMTI_ERROR_INVALID_OBJECT);
  1326     // Method return type signature.
  1327     char* ty_sign = 1 + strchr(signature->as_C_string(), ')');
  1329     if (!VM_GetOrSetLocal::is_assignable(ty_sign, Klass::cast(ob_kh()), current_thread)) {
  1330       return JVMTI_ERROR_TYPE_MISMATCH;
  1332     *ret_ob_h = ob_h;
  1334   return JVMTI_ERROR_NONE;
  1335 } /* end check_top_frame */
  1338 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
  1339 // Main difference is on the last stage in the interpreter.
  1340 // The PopFrame stops method execution to continue execution
  1341 // from the same method call instruction.
  1342 // The ForceEarlyReturn forces return from method so the execution
  1343 // continues at the bytecode following the method call.
  1345 // Threads_lock NOT held, java_thread not protected by lock
  1346 // java_thread - pre-checked
  1348 jvmtiError
  1349 JvmtiEnvBase::force_early_return(JavaThread* java_thread, jvalue value, TosState tos) {
  1350   JavaThread* current_thread = JavaThread::current();
  1351   HandleMark   hm(current_thread);
  1352   uint32_t debug_bits = 0;
  1354   // retrieve or create the state
  1355   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
  1356   if (state == NULL) {
  1357     return JVMTI_ERROR_THREAD_NOT_ALIVE;
  1360   // Check if java_thread is fully suspended
  1361   if (!is_thread_fully_suspended(java_thread,
  1362                                  true /* wait for suspend completion */,
  1363                                  &debug_bits)) {
  1364     return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
  1367   // Check to see if a ForceEarlyReturn was already in progress
  1368   if (state->is_earlyret_pending()) {
  1369     // Probably possible for JVMTI clients to trigger this, but the
  1370     // JPDA backend shouldn't allow this to happen
  1371     return JVMTI_ERROR_INTERNAL;
  1374     // The same as for PopFrame. Workaround bug:
  1375     //  4812902: popFrame hangs if the method is waiting at a synchronize
  1376     // Catch this condition and return an error to avoid hanging.
  1377     // Now JVMTI spec allows an implementation to bail out with an opaque
  1378     // frame error.
  1379     OSThread* osThread = java_thread->osthread();
  1380     if (osThread->get_state() == MONITOR_WAIT) {
  1381       return JVMTI_ERROR_OPAQUE_FRAME;
  1384   Handle ret_ob_h = Handle();
  1385   jvmtiError err = check_top_frame(current_thread, java_thread, value, tos, &ret_ob_h);
  1386   if (err != JVMTI_ERROR_NONE) {
  1387     return err;
  1389   assert(tos != atos || value.l == NULL || ret_ob_h() != NULL,
  1390          "return object oop must not be NULL if jobject is not NULL");
  1392   // Update the thread state to reflect that the top frame must be
  1393   // forced to return.
  1394   // The current frame will be returned later when the suspended
  1395   // thread is resumed and right before returning from VM to Java.
  1396   // (see call_VM_base() in assembler_<cpu>.cpp).
  1398   state->set_earlyret_pending();
  1399   state->set_earlyret_oop(ret_ob_h());
  1400   state->set_earlyret_value(value, tos);
  1402   // Set pending step flag for this early return.
  1403   // It is cleared when next step event is posted.
  1404   state->set_pending_step_for_earlyret();
  1406   return JVMTI_ERROR_NONE;
  1407 } /* end force_early_return */
  1409 void
  1410 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
  1411   if ( _error != JVMTI_ERROR_NONE) {
  1412     // Error occurred in previous iteration so no need to add
  1413     // to the list.
  1414     return;
  1416   if (mon->owner() == _java_thread ) {
  1417     // Filter out on stack monitors collected during stack walk.
  1418     oop obj = (oop)mon->object();
  1419     bool found = false;
  1420     for (int j = 0; j < _owned_monitors_list->length(); j++) {
  1421       jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
  1422       oop check = JNIHandles::resolve(jobj);
  1423       if (check == obj) {
  1424         // On stack monitor already collected during the stack walk.
  1425         found = true;
  1426         break;
  1429     if (found == false) {
  1430       // This is off stack monitor (e.g. acquired via jni MonitorEnter).
  1431       jvmtiError err;
  1432       jvmtiMonitorStackDepthInfo *jmsdi;
  1433       err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
  1434       if (err != JVMTI_ERROR_NONE) {
  1435         _error = err;
  1436         return;
  1438       Handle hobj(obj);
  1439       jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
  1440       // stack depth is unknown for this monitor.
  1441       jmsdi->stack_depth = -1;
  1442       _owned_monitors_list->append(jmsdi);
  1447 #endif // !JVMTI_KERNEL

mercurial