< prev index next >

src/hotspot/share/prims/jvmtiEnvBase.cpp

Print this page

  39 #include "prims/jvmtiExtensions.hpp"
  40 #include "prims/jvmtiImpl.hpp"
  41 #include "prims/jvmtiManageCapabilities.hpp"
  42 #include "prims/jvmtiTagMap.hpp"
  43 #include "prims/jvmtiThreadState.inline.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"

  59 
  60 
  61 ///////////////////////////////////////////////////////////////
  62 //
  63 // JvmtiEnvBase
  64 //
  65 
  66 JvmtiEnvBase* JvmtiEnvBase::_head_environment = NULL;
  67 
  68 bool JvmtiEnvBase::_globally_initialized = false;
  69 volatile bool JvmtiEnvBase::_needs_clean_up = false;
  70 
  71 jvmtiPhase JvmtiEnvBase::_phase = JVMTI_PHASE_PRIMORDIAL;
  72 
  73 volatile int JvmtiEnvBase::_dying_thread_env_iteration_count = 0;
  74 
  75 extern jvmtiInterface_1_ jvmti_Interface;
  76 extern jvmtiInterface_1_ jvmtiTrace_Interface;
  77 
  78 

 542 
 543   for (int i=0; i<length; i++) {
 544     objArray[i] = jni_reference(handles[i]);
 545   }
 546   return objArray;
 547 }
 548 
 549 jthread *
 550 JvmtiEnvBase::new_jthreadArray(int length, Handle *handles) {
 551   return (jthread *) new_jobjectArray(length,handles);
 552 }
 553 
 554 jthreadGroup *
 555 JvmtiEnvBase::new_jthreadGroupArray(int length, Handle *handles) {
 556   return (jthreadGroup *) new_jobjectArray(length,handles);
 557 }
 558 
 559 // return the vframe on the specified thread and depth, NULL if no such frame
 560 // The thread and the oops in the returned vframe might not have been process.
 561 vframe*
 562 JvmtiEnvBase::vframeForNoProcess(JavaThread* java_thread, jint depth) {
 563   if (!java_thread->has_last_Java_frame()) {
 564     return NULL;
 565   }
 566   RegisterMap reg_map(java_thread, true /* update_map */, false /* process_frames */);
 567   vframe *vf = java_thread->last_java_vframe(&reg_map);

 568   int d = 0;
 569   while ((vf != NULL) && (d < depth)) {
 570     vf = vf->java_sender();
 571     d++;
 572   }
 573   return vf;
 574 }
 575 
 576 
 577 //
 578 // utilities: JNI objects
 579 //
 580 
 581 
 582 jclass
 583 JvmtiEnvBase::get_jni_class_non_null(Klass* k) {
 584   assert(k != NULL, "k != NULL");
 585   Thread *thread = Thread::current();
 586   return (jclass)jni_reference(Handle(thread, k->java_mirror()));
 587 }

 590 // Field Information
 591 //
 592 
 593 bool
 594 JvmtiEnvBase::get_field_descriptor(Klass* k, jfieldID field, fieldDescriptor* fd) {
 595   if (!jfieldIDWorkaround::is_valid_jfieldID(k, field)) {
 596     return false;
 597   }
 598   bool found = false;
 599   if (jfieldIDWorkaround::is_static_jfieldID(field)) {
 600     JNIid* id = jfieldIDWorkaround::from_static_jfieldID(field);
 601     found = id->find_local_field(fd);
 602   } else {
 603     // Non-static field. The fieldID is really the offset of the field within the object.
 604     int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);
 605     found = InstanceKlass::cast(k)->find_field_from_offset(offset, false, fd);
 606   }
 607   return found;
 608 }
 609 








































































































































































































 610 //
 611 // Object Monitor Information
 612 //
 613 
 614 //
 615 // Count the number of objects for a lightweight monitor. The hobj
 616 // parameter is object that owns the monitor so this routine will
 617 // count the number of times the same object was locked by frames
 618 // in java_thread.
 619 //
 620 jint
 621 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
 622   jint ret = 0;
 623   if (!java_thread->has_last_Java_frame()) {
 624     return ret;  // no Java frames so no monitors
 625   }
 626 
 627   Thread* current_thread = Thread::current();
 628   ResourceMark rm(current_thread);
 629   HandleMark   hm(current_thread);
 630   RegisterMap  reg_map(java_thread);
 631 
 632   for(javaVFrame *jvf=java_thread->last_java_vframe(&reg_map); jvf != NULL;
 633                                                  jvf = jvf->java_sender()) {

 634     GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 635     if (!mons->is_empty()) {
 636       for (int i = 0; i < mons->length(); i++) {
 637         MonitorInfo *mi = mons->at(i);
 638         if (mi->owner_is_scalar_replaced()) continue;
 639 
 640         // see if owner of the monitor is our object
 641         if (mi->owner() != NULL && mi->owner() == hobj()) {
 642           ret++;
 643         }
 644       }
 645     }
 646   }
 647   return ret;
 648 }
 649 
 650 
 651 
 652 jvmtiError
 653 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread, jobject *monitor_ptr) {
 654   Thread *current_thread = Thread::current();
 655   assert(java_thread->is_handshake_safe_for(current_thread),
 656          "call by myself or at handshake");
 657   oop obj = NULL;
 658   // The ObjectMonitor* can't be async deflated since we are either
 659   // at a safepoint or the calling thread is operating on itself so
 660   // it cannot leave the underlying wait()/enter() call.
 661   ObjectMonitor *mon = java_thread->current_waiting_monitor();
 662   if (mon == NULL) {
 663     // thread is not doing an Object.wait() call
 664     mon = java_thread->current_pending_monitor();
 665     if (mon != NULL) {
 666       // The thread is trying to enter() an ObjectMonitor.
 667       obj = mon->object();
 668       assert(obj != NULL, "ObjectMonitor should have a valid object!");
 669     }
 670     // implied else: no contended ObjectMonitor
 671   } else {
 672     // thread is doing an Object.wait() call
 673     obj = mon->object();
 674     assert(obj != NULL, "Object.wait() should have an object");
 675   }
 676 
 677   if (obj == NULL) {
 678     *monitor_ptr = NULL;
 679   } else {
 680     HandleMark hm(current_thread);
 681     Handle     hobj(current_thread, obj);
 682     *monitor_ptr = jni_reference(calling_thread, hobj);
 683   }
 684   return JVMTI_ERROR_NONE;
 685 }
 686 
 687 
 688 jvmtiError
 689 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
 690                                  GrowableArray<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.
 696   jvmtiError err = JVMTI_ERROR_NONE;
 697   Thread *current_thread = Thread::current();
 698   assert(java_thread->is_handshake_safe_for(current_thread),
 699          "call by myself or at handshake");
 700 
 701   if (java_thread->has_last_Java_frame()) {
 702     ResourceMark rm(current_thread);
 703     HandleMark   hm(current_thread);
 704     RegisterMap  reg_map(java_thread);
 705 
 706     int depth = 0;
 707     for (javaVFrame *jvf = java_thread->last_java_vframe(&reg_map); jvf != NULL;

 708          jvf = jvf->java_sender()) {
 709       if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 710         // add locked objects for this frame into list
 711         err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 712         if (err != JVMTI_ERROR_NONE) {
 713           return err;
 714         }
 715       }
 716     }
 717   }
 718 
 719   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 720   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 721   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 722   err = jmc.error();
 723 
 724   return err;
 725 }
 726 






























 727 // Save JNI local handles for any objects that this frame owns.
 728 jvmtiError
 729 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
 730                                  javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, jint stack_depth) {
 731   jvmtiError err = JVMTI_ERROR_NONE;
 732   Thread* current_thread = Thread::current();
 733   ResourceMark rm(current_thread);
 734   HandleMark   hm(current_thread);
 735 
 736   GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 737   if (mons->is_empty()) {
 738     return err;  // this javaVFrame holds no monitors
 739   }
 740 
 741   oop wait_obj = NULL;
 742   {
 743     // The ObjectMonitor* can't be async deflated since we are either
 744     // at a safepoint or the calling thread is operating on itself so
 745     // it cannot leave the underlying wait() call.
 746     // Save object of current wait() call (if any) for later comparison.

 799         // already have this object so don't include it
 800         continue;
 801       }
 802     }
 803 
 804     // add the owning object to our list
 805     jvmtiMonitorStackDepthInfo *jmsdi;
 806     err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
 807     if (err != JVMTI_ERROR_NONE) {
 808         return err;
 809     }
 810     Handle hobj(Thread::current(), obj);
 811     jmsdi->monitor = jni_reference(calling_thread, hobj);
 812     jmsdi->stack_depth = stack_depth;
 813     owned_monitors_list->append(jmsdi);
 814   }
 815 
 816   return err;
 817 }
 818 






























































 819 jvmtiError
 820 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
 821                               jint start_depth, jint max_count,
 822                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
 823 #ifdef ASSERT
 824   uint32_t debug_bits = 0;
 825 #endif
 826   Thread *current_thread = Thread::current();
 827   assert(SafepointSynchronize::is_at_safepoint() ||
 828          java_thread->is_handshake_safe_for(current_thread),
 829          "call by myself / at safepoint / at handshake");
 830   int count = 0;


 831   if (java_thread->has_last_Java_frame()) {
 832     RegisterMap reg_map(java_thread);
 833     ResourceMark rm(current_thread);
 834     javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
 835     HandleMark hm(current_thread);
 836     if (start_depth != 0) {
 837       if (start_depth > 0) {
 838         for (int j = 0; j < start_depth && jvf != NULL; j++) {
 839           jvf = jvf->java_sender();
 840         }
 841         if (jvf == NULL) {
 842           // start_depth is deeper than the stack depth
 843           return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 844         }
 845       } else { // start_depth < 0
 846         // we are referencing the starting depth based on the oldest
 847         // part of the stack.
 848         // optimize to limit the number of times that java_sender() is called
 849         javaVFrame *jvf_cursor = jvf;
 850         javaVFrame *jvf_prev = NULL;
 851         javaVFrame *jvf_prev_prev = NULL;
 852         int j = 0;
 853         while (jvf_cursor != NULL) {
 854           jvf_prev_prev = jvf_prev;
 855           jvf_prev = jvf_cursor;
 856           for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
 857             jvf_cursor = jvf_cursor->java_sender();
 858           }
 859         }
 860         if (j == start_depth) {
 861           // previous pointer is exactly where we want to start
 862           jvf = jvf_prev;
 863         } else {
 864           // we need to back up further to get to the right place
 865           if (jvf_prev_prev == NULL) {
 866             // the -start_depth is greater than the stack depth
 867             return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 868           }
 869           // j now is the number of frames on the stack starting with
 870           // jvf_prev, we start from jvf_prev_prev and move older on
 871           // the stack that many, the result is -start_depth frames
 872           // remaining.
 873           jvf = jvf_prev_prev;
 874           for (; j < 0; j++) {
 875             jvf = jvf->java_sender();
 876           }
 877         }
 878       }
 879     }
 880     for (; count < max_count && jvf != NULL; count++) {
 881       frame_buffer[count].method = jvf->method()->jmethod_id();
 882       frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
 883       jvf = jvf->java_sender();
 884     }
 885   } else {

 886     if (start_depth != 0) {
 887       // no frames and there is a starting depth
 888       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 889     }
 890   }
 891   *count_ptr = count;































 892   return JVMTI_ERROR_NONE;
 893 }
 894 
 895 jvmtiError
 896 JvmtiEnvBase::get_frame_count(JvmtiThreadState *state, jint *count_ptr) {
 897   assert((state != NULL),
 898          "JavaThread should create JvmtiThreadState before calling this method");
 899   *count_ptr = state->count_frames();





 900   return JVMTI_ERROR_NONE;
 901 }
 902 
 903 jvmtiError
 904 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
 905                                  jmethodID* method_ptr, jlocation* location_ptr) {
 906 #ifdef ASSERT
 907   uint32_t debug_bits = 0;
 908 #endif
 909   Thread* current_thread = Thread::current();
 910   assert(java_thread->is_handshake_safe_for(current_thread),
 911          "call by myself or at handshake");
 912   ResourceMark rm(current_thread);
 913 
 914   vframe *vf = vframeForNoProcess(java_thread, depth);
 915   if (vf == NULL) {
 916     return JVMTI_ERROR_NO_MORE_FRAMES;
 917   }
 918 
 919   // vframeFor should return a java frame. If it doesn't
 920   // it means we've got an internal error and we return the
 921   // error in product mode. In debug mode we will instead
 922   // attempt to cast the vframe to a javaVFrame and will
 923   // cause an assertion/crash to allow further diagnosis.
 924 #ifdef PRODUCT
 925   if (!vf->is_java_frame()) {
 926     return JVMTI_ERROR_INTERNAL;
 927   }
 928 #endif
 929 
 930   HandleMark hm(current_thread);
 931   javaVFrame *jvf = javaVFrame::cast(vf);
 932   Method* method = jvf->method();
 933   if (method->is_native()) {
 934     *location_ptr = -1;
 935   } else {
 936     *location_ptr = jvf->bci();
 937   }
 938   *method_ptr = method->jmethod_id();
 939 
 940   return JVMTI_ERROR_NONE;
 941 }
 942 

























































































 943 
 944 jvmtiError
 945 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
 946   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 947   Thread* current_thread = VMThread::vm_thread();
 948   assert(current_thread == Thread::current(), "must be");
 949 
 950   HandleMark hm(current_thread);
 951   Handle hobj;
 952 
 953   // Check arguments
 954   {
 955     oop mirror = JNIHandles::resolve_external_guard(object);
 956     NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
 957     NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
 958 
 959     hobj = Handle(current_thread, mirror);
 960   }
 961 
 962   ThreadsListHandle tlh(current_thread);

 981         }
 982         // implied else: no owner
 983       } else {
 984         // this object has a heavyweight monitor
 985         mon = mark.monitor();
 986 
 987         // The owner field of a heavyweight monitor may be NULL for no
 988         // owner, a JavaThread * or it may still be the address of the
 989         // Lock word in a JavaThread's stack. A monitor can be inflated
 990         // by a non-owning JavaThread, but only the owning JavaThread
 991         // can change the owner field from the Lock word to the
 992         // JavaThread * and it may not have done that yet.
 993         owner = (address)mon->owner();
 994       }
 995     }
 996 
 997     if (owner != NULL) {
 998       // This monitor is owned so we have to find the owning JavaThread.
 999       owning_thread = Threads::owning_thread_from_monitor_owner(tlh.list(), owner);
1000       assert(owning_thread != NULL, "owning JavaThread must not be NULL");
1001       Handle     th(current_thread, owning_thread->threadObj());
1002       ret.owner = (jthread)jni_reference(calling_thread, th);
1003     }
1004 
1005     if (owning_thread != NULL) {  // monitor is owned
1006       // The recursions field of a monitor does not reflect recursions
1007       // as lightweight locks before inflating the monitor are not included.
1008       // We have to count the number of recursive monitor entries the hard way.
1009       // We pass a handle to survive any GCs along the way.
1010       ret.entry_count = count_locked_objects(owning_thread, hobj);
1011     }
1012     // implied else: entry_count == 0
1013   }
1014 
1015   jint nWant = 0, nWait = 0;
1016   if (mon != NULL) {
1017     // this object has a heavyweight monitor
1018     nWant = mon->contentions(); // # of threads contending for monitor
1019     nWait = mon->waiters();     // # of threads in Object.wait()
1020     ret.waiter_count = nWant + nWait;
1021     ret.notify_waiter_count = nWait;

1044 
1045     // Number of waiters may actually be less than the waiter count.
1046     // So NULL out memory so that unused memory will be NULL.
1047     memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1048     memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1049 
1050     if (ret.waiter_count > 0) {
1051       // we have contending and/or waiting threads
1052       if (nWant > 0) {
1053         // we have contending threads
1054         ResourceMark rm(current_thread);
1055         // get_pending_threads returns only java thread so we do not need to
1056         // check for non java threads.
1057         GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(tlh.list(), nWant, (address)mon);
1058         if (wantList->length() < nWant) {
1059           // robustness: the pending list has gotten smaller
1060           nWant = wantList->length();
1061         }
1062         for (int i = 0; i < nWant; i++) {
1063           JavaThread *pending_thread = wantList->at(i);
1064           Handle th(current_thread, pending_thread->threadObj());
1065           ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1066         }
1067       }
1068       if (nWait > 0) {
1069         // we have threads in Object.wait()
1070         int offset = nWant;  // add after any contending threads
1071         ObjectWaiter *waiter = mon->first_waiter();
1072         for (int i = 0, j = 0; i < nWait; i++) {
1073           if (waiter == NULL) {
1074             // robustness: the waiting list has gotten smaller
1075             nWait = j;
1076             break;
1077           }
1078           JavaThread *w = mon->thread_of_waiter(waiter);
1079           if (w != NULL) {
1080             // If the thread was found on the ObjectWaiter list, then
1081             // it has not been notified. This thread can't change the
1082             // state of the monitor so it doesn't need to be suspended.
1083             Handle th(current_thread, w->threadObj());
1084             ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1085             ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1086           }
1087           waiter = mon->next_waiter(waiter);
1088         }
1089       }
1090     } // ThreadsListHandle is destroyed here.
1091 
1092     // Adjust count. nWant and nWait count values may be less than original.
1093     ret.waiter_count = nWant + nWait;
1094     ret.notify_waiter_count = nWait;
1095   } else {
1096     // this object has a lightweight monitor and we have nothing more
1097     // to do here because the defaults are just fine.
1098   }
1099 
1100   // we don't update return parameter unless everything worked
1101   *info_ptr = ret;
1102 
1103   return JVMTI_ERROR_NONE;
1104 }
1105 


















































































































































1106 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1107   _env = env;
1108   _allocations = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<unsigned char*>(20, mtServiceability);
1109   _failed = false;
1110 }
1111 ResourceTracker::~ResourceTracker() {
1112   if (_failed) {
1113     for (int i=0; i<_allocations->length(); i++) {
1114       _env->deallocate(_allocations->at(i));
1115     }
1116   }
1117   delete _allocations;
1118 }
1119 
1120 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1121   unsigned char *ptr;
1122   jvmtiError err = _env->allocate(size, &ptr);
1123   if (err == JVMTI_ERROR_NONE) {
1124     _allocations->append(ptr);
1125     *mem_ptr = ptr;

1132 
1133 unsigned char* ResourceTracker::allocate(jlong size) {
1134   unsigned char* ptr;
1135   allocate(size, &ptr);
1136   return ptr;
1137 }
1138 
1139 char* ResourceTracker::strdup(const char* str) {
1140   char *dup_str = (char*)allocate(strlen(str)+1);
1141   if (dup_str != NULL) {
1142     strcpy(dup_str, str);
1143   }
1144   return dup_str;
1145 }
1146 
1147 struct StackInfoNode {
1148   struct StackInfoNode *next;
1149   jvmtiStackInfo info;
1150 };
1151 

1152 // Create a jvmtiStackInfo inside a linked list node and create a
1153 // buffer for the frame information, both allocated as resource objects.
1154 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1155 // Note that either or both of thr and thread_oop
1156 // may be null if the thread is new or has exited.
1157 void
1158 MultipleStackTracesCollector::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1159 #ifdef ASSERT
1160   Thread *current_thread = Thread::current();
1161   assert(SafepointSynchronize::is_at_safepoint() ||

1162          thr->is_handshake_safe_for(current_thread),
1163          "call by myself / at safepoint / at handshake");
1164 #endif
1165 
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;
1173 
1174   if (thread_oop != NULL) {
1175     // get most state bits
1176     state = (jint)java_lang_Thread::get_thread_status(thread_oop);
1177   }
1178 
1179   if (thr != NULL) {    // add more state bits if there is a JavaThead to query
1180     if (thr->is_suspended()) {
1181       state |= JVMTI_THREAD_STATE_SUSPENDED;
1182     }
1183     JavaThreadState jts = thr->thread_state();
1184     if (jts == _thread_in_native) {
1185       state |= JVMTI_THREAD_STATE_IN_NATIVE;
1186     }
1187     if (thr->is_interrupted(false)) {
1188       state |= JVMTI_THREAD_STATE_INTERRUPTED;
1189     }
1190   }
1191   infop->state = state;
1192 
1193   if (thr != NULL && (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1194     infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1195     env()->get_stack_trace(thr, 0, max_frame_count(),
1196                            infop->frame_buffer, &(infop->frame_count));
1197   } else {
1198     infop->frame_buffer = NULL;
1199     infop->frame_count = 0;




1200   }
1201   _frame_count_total += infop->frame_count;

1202 }
1203 
1204 // Based on the stack information in the linked list, allocate memory
1205 // block to return and fill it from the info in the linked list.
1206 void
1207 MultipleStackTracesCollector::allocate_and_fill_stacks(jint thread_count) {
1208   // do I need to worry about alignment issues?
1209   jlong alloc_size =  thread_count       * sizeof(jvmtiStackInfo)
1210                     + _frame_count_total * sizeof(jvmtiFrameInfo);
1211   env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1212 
1213   // pointers to move through the newly allocated space as it is filled in
1214   jvmtiStackInfo *si = _stack_info + thread_count;      // bottom of stack info
1215   jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si;            // is the top of frame info
1216 
1217   // copy information in resource area into allocated buffer
1218   // insert stack info backwards since linked list is backwards
1219   // insert frame info forwards
1220   // walk the StackInfoNodes
1221   for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {

1235   assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1236          "the last copied frame info must be the last record");
1237 }
1238 
1239 
1240 void
1241 VM_GetThreadListStackTraces::doit() {
1242   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1243 
1244   ResourceMark rm;
1245   ThreadsListHandle tlh;
1246   for (int i = 0; i < _thread_count; ++i) {
1247     jthread jt = _thread_list[i];
1248     JavaThread* java_thread = NULL;
1249     oop thread_oop = NULL;
1250     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), jt, &java_thread, &thread_oop);
1251     if (err != JVMTI_ERROR_NONE) {
1252       // We got an error code so we don't have a JavaThread *, but
1253       // only return an error from here if we didn't get a valid
1254       // thread_oop.


1255       if (thread_oop == NULL) {
1256         _collector.set_result(err);
1257         return;
1258       }
1259       // We have a valid thread_oop.
1260     }
1261     _collector.fill_frames(jt, java_thread, thread_oop);
1262   }
1263   _collector.allocate_and_fill_stacks(_thread_count);
1264 }
1265 
1266 void
1267 GetSingleStackTraceClosure::do_thread(Thread *target) {
1268   JavaThread *jt = JavaThread::cast(target);
1269   oop thread_oop = jt->threadObj();
1270 
1271   if (!jt->is_exiting() && thread_oop != NULL) {
1272     ResourceMark rm;
1273     _collector.fill_frames(_jthread, jt, thread_oop);
1274     _collector.allocate_and_fill_stacks(1);
1275   }
1276 }
1277 
1278 void
1279 VM_GetAllStackTraces::doit() {
1280   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1281 
1282   ResourceMark rm;
1283   _final_thread_count = 0;
1284   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1285     oop thread_oop = jt->threadObj();
1286     if (thread_oop != NULL &&
1287         !jt->is_exiting() &&
1288         java_lang_Thread::is_alive(thread_oop) &&
1289         !jt->is_hidden_from_external_view()) {
1290       ++_final_thread_count;
1291       // Handle block of the calling thread is used to create local refs.
1292       _collector.fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
1293                              jt, thread_oop);
1294     }
1295   }

1597   // (see call_VM_base() in assembler_<cpu>.cpp).
1598 
1599   // It's fine to update the thread state here because no JVMTI events
1600   // shall be posted for this PopFrame.
1601 
1602   if (!java_thread->is_exiting() && java_thread->threadObj() != NULL) {
1603     _state->update_for_pop_top_frame();
1604     java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
1605     // Set pending step flag for this popframe and it is cleared when next
1606     // step event is posted.
1607     _state->set_pending_step_for_popframe();
1608     _result = JVMTI_ERROR_NONE;
1609   }
1610 }
1611 
1612 void
1613 SetFramePopClosure::doit(Thread *target, bool self) {
1614   ResourceMark rm;
1615   JavaThread* java_thread = JavaThread::cast(target);
1616 
1617   assert(_state->get_thread() == java_thread, "Must be");

1618 
1619   if (!self && !java_thread->is_suspended()) {
1620     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1621     return;
1622   }
1623 
1624   vframe *vf = JvmtiEnvBase::vframeForNoProcess(java_thread, _depth);
1625   if (vf == NULL) {
1626     _result = JVMTI_ERROR_NO_MORE_FRAMES;
1627     return;
1628   }
1629 
1630   if (!vf->is_java_frame() || ((javaVFrame*) vf)->method()->is_native()) {
1631     _result = JVMTI_ERROR_OPAQUE_FRAME;
1632     return;
1633   }
1634 
1635   assert(vf->frame_pointer() != NULL, "frame pointer mustn't be NULL");
1636   if (java_thread->is_exiting() || java_thread->threadObj() == NULL) {
1637     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
1638   }
1639   int frame_number = _state->count_frames() - _depth;
1640   _state->env_thread_state((JvmtiEnvBase*)_env)->set_frame_pop(frame_number);
1641   _result = JVMTI_ERROR_NONE;
1642 }
1643 
1644 void
1645 GetOwnedMonitorInfoClosure::do_thread(Thread *target) {
1646   JavaThread *jt = JavaThread::cast(target);
1647   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
1648     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread,
1649                                                          jt,
1650                                                          _owned_monitors_list);
1651   }
1652 }
1653 
1654 void
1655 GetCurrentContendedMonitorClosure::do_thread(Thread *target) {
1656   JavaThread *jt = JavaThread::cast(target);
1657   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
1658     _result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor(_calling_thread,
1659                                                                     jt,
1660                                                                     _owned_monitor_ptr);
1661   }
1662 }
1663 














1664 void
1665 GetStackTraceClosure::do_thread(Thread *target) {
1666   JavaThread *jt = JavaThread::cast(target);
1667   if (!jt->is_exiting() && jt->threadObj() != NULL) {
1668     _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jt,
1669                                                       _start_depth, _max_count,
1670                                                       _frame_buffer, _count_ptr);
1671   }
1672 }
1673 


















































1674 void
1675 GetFrameCountClosure::do_thread(Thread *target) {
1676   JavaThread* jt = _state->get_thread();
1677   assert(target == jt, "just checking");
1678   if (!jt->is_exiting() && jt->threadObj() != NULL) {
1679     _result = ((JvmtiEnvBase*)_env)->get_frame_count(_state, _count_ptr);
1680   }
1681 }
1682 
1683 void
1684 GetFrameLocationClosure::do_thread(Thread *target) {
1685   JavaThread *jt = JavaThread::cast(target);
1686   if (!jt->is_exiting() && jt->threadObj() != NULL) {
1687     _result = ((JvmtiEnvBase*)_env)->get_frame_location(jt, _depth,
1688                                                         _method_ptr, _location_ptr);
1689   }
1690 }



























































































  39 #include "prims/jvmtiExtensions.hpp"
  40 #include "prims/jvmtiImpl.hpp"
  41 #include "prims/jvmtiManageCapabilities.hpp"
  42 #include "prims/jvmtiTagMap.hpp"
  43 #include "prims/jvmtiThreadState.inline.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"
  59 #include "services/threadService.hpp"
  60 
  61 
  62 ///////////////////////////////////////////////////////////////
  63 //
  64 // JvmtiEnvBase
  65 //
  66 
  67 JvmtiEnvBase* JvmtiEnvBase::_head_environment = NULL;
  68 
  69 bool JvmtiEnvBase::_globally_initialized = false;
  70 volatile bool JvmtiEnvBase::_needs_clean_up = false;
  71 
  72 jvmtiPhase JvmtiEnvBase::_phase = JVMTI_PHASE_PRIMORDIAL;
  73 
  74 volatile int JvmtiEnvBase::_dying_thread_env_iteration_count = 0;
  75 
  76 extern jvmtiInterface_1_ jvmti_Interface;
  77 extern jvmtiInterface_1_ jvmtiTrace_Interface;
  78 
  79 

 543 
 544   for (int i=0; i<length; i++) {
 545     objArray[i] = jni_reference(handles[i]);
 546   }
 547   return objArray;
 548 }
 549 
 550 jthread *
 551 JvmtiEnvBase::new_jthreadArray(int length, Handle *handles) {
 552   return (jthread *) new_jobjectArray(length,handles);
 553 }
 554 
 555 jthreadGroup *
 556 JvmtiEnvBase::new_jthreadGroupArray(int length, Handle *handles) {
 557   return (jthreadGroup *) new_jobjectArray(length,handles);
 558 }
 559 
 560 // return the vframe on the specified thread and depth, NULL if no such frame
 561 // The thread and the oops in the returned vframe might not have been process.
 562 vframe*
 563 JvmtiEnvBase::vframeForNoProcess(JavaThread* java_thread, jint depth, bool for_cont) {
 564   if (!java_thread->has_last_Java_frame()) {
 565     return NULL;
 566   }
 567   RegisterMap reg_map(java_thread, true /* update_map */, false /* process_frames */, true /* walk_cont */);
 568   vframe *vf = for_cont ? JvmtiEnvBase::get_last_java_vframe(java_thread, &reg_map)
 569                         : java_thread->last_java_vframe(&reg_map);
 570   int d = 0;
 571   while ((vf != NULL) && (d < depth)) {
 572     vf = vf->java_sender();
 573     d++;
 574   }
 575   return vf;
 576 }
 577 
 578 
 579 //
 580 // utilities: JNI objects
 581 //
 582 
 583 
 584 jclass
 585 JvmtiEnvBase::get_jni_class_non_null(Klass* k) {
 586   assert(k != NULL, "k != NULL");
 587   Thread *thread = Thread::current();
 588   return (jclass)jni_reference(Handle(thread, k->java_mirror()));
 589 }

 592 // Field Information
 593 //
 594 
 595 bool
 596 JvmtiEnvBase::get_field_descriptor(Klass* k, jfieldID field, fieldDescriptor* fd) {
 597   if (!jfieldIDWorkaround::is_valid_jfieldID(k, field)) {
 598     return false;
 599   }
 600   bool found = false;
 601   if (jfieldIDWorkaround::is_static_jfieldID(field)) {
 602     JNIid* id = jfieldIDWorkaround::from_static_jfieldID(field);
 603     found = id->find_local_field(fd);
 604   } else {
 605     // Non-static field. The fieldID is really the offset of the field within the object.
 606     int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);
 607     found = InstanceKlass::cast(k)->find_field_from_offset(offset, false, fd);
 608   }
 609   return found;
 610 }
 611 
 612 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue);
 613 
 614 javaVFrame*
 615 JvmtiEnvBase::check_and_skip_hidden_frames(bool is_in_VTMT, javaVFrame* jvf) {
 616   // The second condition is needed to hide notification methods.
 617   if (!is_in_VTMT && (jvf == NULL || !jvf->method()->jvmti_mount_transition())) {
 618     return jvf; // no frames to skip
 619   }
 620   javaVFrame* jvf_saved = jvf;
 621   // find jvf with a method annotated with @JvmtiMountTransition
 622   for ( ; jvf != NULL; jvf = jvf->java_sender()) {
 623     if (jvf->method()->jvmti_mount_transition()) {
 624       jvf = jvf->java_sender(); // skip annotated method
 625       break;
 626     }
 627     if (jvf->method()->changes_current_thread()) {
 628       break;
 629     }
 630     // skip frame above annotated method
 631   }
 632   if (jvf == NULL) { // TMP workaround for stability until the root cause is fixed
 633     jvf = jvf_saved;
 634     assert (jvf != NULL, "");
 635     assert (dbg_is_safe(jvf, -1), "");
 636     assert (jvf->register_map() != NULL, "");
 637     assert (dbg_is_safe(jvf->register_map(), -1), "");
 638     jvf->restore_register_map(); // we're returning to a frame we've walked past and might walk from again
 639   }
 640   return jvf;
 641 }
 642 
 643 javaVFrame*
 644 JvmtiEnvBase::check_and_skip_hidden_frames(JavaThread* jt, javaVFrame* jvf) {
 645   jvf = check_and_skip_hidden_frames(jt->is_in_VTMT(), jvf);
 646   return jvf;
 647 }
 648 
 649 javaVFrame*
 650 JvmtiEnvBase::check_and_skip_hidden_frames(oop vthread, javaVFrame* jvf) {
 651   JvmtiThreadState* state = java_lang_Thread::jvmti_thread_state(vthread);
 652   if (state == NULL) {
 653     return jvf; // nothing to skip
 654   }
 655   jvf = check_and_skip_hidden_frames(state->is_in_VTMT(), jvf);
 656   return jvf;
 657 }
 658 
 659 bool
 660 JvmtiEnvBase::is_vthread_alive(oop vt) {
 661   assert(java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::NEW, "sanity check");
 662   return java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::TERMINATED;
 663 }
 664 
 665 javaVFrame*
 666 JvmtiEnvBase::get_vthread_jvf(oop vthread) {
 667   assert(java_lang_VirtualThread::state(vthread) != java_lang_VirtualThread::NEW, "sanity check");
 668   assert(java_lang_VirtualThread::state(vthread) != java_lang_VirtualThread::TERMINATED, "sanity check");
 669 
 670   Thread* cur_thread = Thread::current();
 671   oop cont = java_lang_VirtualThread::continuation(vthread);
 672   javaVFrame* jvf = NULL;
 673 
 674   assert(cont != NULL, "virtual thread continuation must not be NULL");
 675 
 676   oop carrier_thread = java_lang_VirtualThread::carrier_thread(vthread);
 677   // Returned carrier_thread can be NULL for a mounted continuation.
 678   // Then treat it as an unmounted case.
 679   if (jdk_internal_vm_Continuation::is_mounted(cont) && carrier_thread != NULL) {
 680     JavaThread* java_thread = java_lang_Thread::thread(carrier_thread);
 681 
 682     if (!java_thread->has_last_Java_frame()) {
 683       // TBD: This is a temporary work around to avoid a guarantee caused by
 684       // the native enterSpecial frame on the top. No frames will be found
 685       // by the JVMTI functions such as GetStackTrace.
 686       return NULL;
 687     }
 688     vframeStream vfs(java_thread, Handle(cur_thread, Continuation::continuation_scope(cont)));
 689     jvf = vfs.at_end() ? NULL : vfs.asJavaVFrame();
 690     jvf = check_and_skip_hidden_frames(java_thread, jvf);
 691   } else {
 692     vframeStream vfs(cont);
 693     jvf = vfs.at_end() ? NULL : vfs.asJavaVFrame();
 694     jvf = check_and_skip_hidden_frames(vthread, jvf);
 695   }
 696   return jvf;
 697 }
 698 
 699 javaVFrame*
 700 JvmtiEnvBase::get_last_java_vframe(JavaThread* jt, RegisterMap* reg_map_p) {
 701   // Strip vthread frames in case of carrier thread with mounted continuation.
 702   javaVFrame *jvf = JvmtiEnvBase::cthread_with_continuation(jt) ?
 703                         jt->vthread_carrier_last_java_vframe(reg_map_p) :
 704                         jt->last_java_vframe(reg_map_p);
 705   jvf = check_and_skip_hidden_frames(jt, jvf);
 706   return jvf;
 707 }
 708 
 709 jint
 710 JvmtiEnvBase::get_thread_state(oop thread_oop, JavaThread* jt) {
 711   jint state = 0;
 712 
 713   if (thread_oop != NULL) {
 714     // get most state bits
 715     state = (jint)java_lang_Thread::get_thread_status(thread_oop);
 716   }
 717   if (jt != NULL) {
 718     // We have a JavaThread* so add more state bits.
 719     JavaThreadState jts = jt->thread_state();
 720 
 721     if (jt->is_thread_suspended() ||
 722         (jt->vthread() == thread_oop && jt->is_suspended())) {
 723       // Suspended non-virtual thread.
 724       state |= JVMTI_THREAD_STATE_SUSPENDED;
 725     }
 726     if (jts == _thread_in_native) {
 727       state |= JVMTI_THREAD_STATE_IN_NATIVE;
 728     }
 729     if (jt->is_interrupted(false)) {
 730       state |= JVMTI_THREAD_STATE_INTERRUPTED;
 731     }
 732   }
 733   return state;
 734 }
 735 
 736 jint
 737 JvmtiEnvBase::get_vthread_state(oop thread_oop) {
 738   jshort vt_state = java_lang_VirtualThread::state(thread_oop);
 739   jint state = (jint) java_lang_VirtualThread::map_state_to_thread_status(vt_state);
 740   bool ext_suspended = JvmtiVTSuspender::is_vthread_suspended(thread_oop);
 741 
 742   if (ext_suspended && ((state & JVMTI_THREAD_STATE_ALIVE) != 0)) {
 743     state &= ~java_lang_VirtualThread::RUNNING;
 744     state |= JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE | JVMTI_THREAD_STATE_SUSPENDED;
 745   }
 746   if (java_lang_Thread::interrupted(thread_oop)) {
 747     state |= JVMTI_THREAD_STATE_INTERRUPTED;
 748   }
 749   return state;
 750 }
 751 
 752 int
 753 JvmtiEnvBase::get_live_threads(JavaThread* current_thread, Handle group_hdl, Handle **thread_objs_p) {
 754   int count = 0;
 755   Handle *thread_objs = NULL;
 756   ThreadsListEnumerator tle(current_thread, true);
 757   int nthreads = tle.num_threads();
 758   if (nthreads > 0) {
 759     thread_objs = NEW_RESOURCE_ARRAY(Handle, nthreads);
 760     NULL_CHECK(thread_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 761     for (int i = 0; i < nthreads; i++) {
 762       Handle thread = tle.get_threadObj(i);
 763       if (thread()->is_a(vmClasses::Thread_klass()) && java_lang_Thread::threadGroup(thread()) == group_hdl()) {
 764         thread_objs[count++] = thread;
 765       }
 766     }
 767   }
 768   *thread_objs_p = thread_objs;
 769   return count;
 770 }
 771 
 772 int
 773 JvmtiEnvBase::get_subgroups(JavaThread* current_thread, Handle group_hdl, Handle **group_objs_p) {
 774   ObjectLocker ol(group_hdl, current_thread);
 775 
 776   int ngroups  = java_lang_ThreadGroup::ngroups(group_hdl());
 777   int nweaks  = java_lang_ThreadGroup::nweaks(group_hdl());
 778 
 779   int count = 0;
 780   Handle *group_objs = NULL;
 781   if (ngroups > 0 || nweaks > 0) {
 782     group_objs = NEW_RESOURCE_ARRAY(Handle, ngroups + nweaks);
 783     NULL_CHECK(group_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 784 
 785     // strongly reachable subgroups
 786     if (ngroups > 0) {
 787       objArrayOop groups = java_lang_ThreadGroup::groups(group_hdl());
 788       for (int j = 0; j < ngroups; j++) {
 789         oop group_obj = groups->obj_at(j);
 790         assert(group_obj != NULL, "group_obj != NULL");
 791         group_objs[count++] = Handle(current_thread, group_obj);
 792       }
 793     }
 794 
 795     // weakly reachable subgroups
 796     if (nweaks > 0) {
 797       objArrayOop weaks = java_lang_ThreadGroup::weaks(group_hdl());
 798       for (int j = 0; j < nweaks; j++) {
 799         oop weak_obj = weaks->obj_at(j);
 800         assert(weak_obj != NULL, "weak_obj != NULL");
 801         oop group_obj = java_lang_ref_Reference::unknown_referent(weak_obj);
 802         if (group_obj != NULL) {
 803           group_objs[count++] = Handle(current_thread, group_obj);
 804         }
 805       }
 806     }
 807   }
 808   *group_objs_p = group_objs;
 809   return count;
 810 }
 811 
 812 //
 813 // Object Monitor Information
 814 //
 815 
 816 //
 817 // Count the number of objects for a lightweight monitor. The hobj
 818 // parameter is object that owns the monitor so this routine will
 819 // count the number of times the same object was locked by frames
 820 // in java_thread.
 821 //
 822 jint
 823 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
 824   jint ret = 0;
 825   if (!java_thread->has_last_Java_frame()) {
 826     return ret;  // no Java frames so no monitors
 827   }
 828 
 829   Thread* current_thread = Thread::current();
 830   ResourceMark rm(current_thread);
 831   HandleMark   hm(current_thread);
 832   RegisterMap  reg_map(java_thread, true, true);
 833 
 834   for (javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
 835        jvf != NULL;
 836        jvf = jvf->java_sender()) {
 837     GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 838     if (!mons->is_empty()) {
 839       for (int i = 0; i < mons->length(); i++) {
 840         MonitorInfo *mi = mons->at(i);
 841         if (mi->owner_is_scalar_replaced()) continue;
 842 
 843         // see if owner of the monitor is our object
 844         if (mi->owner() != NULL && mi->owner() == hobj()) {
 845           ret++;
 846         }
 847       }
 848     }
 849   }
 850   return ret;
 851 }
 852 


 853 jvmtiError
 854 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread, jobject *monitor_ptr) {
 855   Thread *current_thread = Thread::current();
 856   assert(java_thread->is_handshake_safe_for(current_thread),
 857          "call by myself or at handshake");
 858   oop obj = NULL;
 859   // The ObjectMonitor* can't be async deflated since we are either
 860   // at a safepoint or the calling thread is operating on itself so
 861   // it cannot leave the underlying wait()/enter() call.
 862   ObjectMonitor *mon = java_thread->current_waiting_monitor();
 863   if (mon == NULL) {
 864     // thread is not doing an Object.wait() call
 865     mon = java_thread->current_pending_monitor();
 866     if (mon != NULL) {
 867       // The thread is trying to enter() an ObjectMonitor.
 868       obj = mon->object();
 869       assert(obj != NULL, "ObjectMonitor should have a valid object!");
 870     }
 871     // implied else: no contended ObjectMonitor
 872   } else {
 873     // thread is doing an Object.wait() call
 874     obj = mon->object();
 875     assert(obj != NULL, "Object.wait() should have an object");
 876   }
 877 
 878   if (obj == NULL) {
 879     *monitor_ptr = NULL;
 880   } else {
 881     HandleMark hm(current_thread);
 882     Handle     hobj(current_thread, obj);
 883     *monitor_ptr = jni_reference(calling_thread, hobj);
 884   }
 885   return JVMTI_ERROR_NONE;
 886 }
 887 

 888 jvmtiError
 889 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
 890                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 891   // Note:
 892   // calling_thread is the thread that requested the list of monitors for java_thread.
 893   // java_thread is the thread owning the monitors.
 894   // current_thread is the thread executing this code, can be a non-JavaThread (e.g. VM Thread).
 895   // And they all may be different threads.
 896   jvmtiError err = JVMTI_ERROR_NONE;
 897   Thread *current_thread = Thread::current();
 898   assert(java_thread->is_handshake_safe_for(current_thread),
 899          "call by myself or at handshake");
 900 
 901   if (java_thread->has_last_Java_frame()) {
 902     ResourceMark rm(current_thread);
 903     HandleMark   hm(current_thread);
 904     RegisterMap  reg_map(java_thread);
 905 
 906     int depth = 0;
 907     for (javaVFrame *jvf = JvmtiEnvBase::get_last_java_vframe(java_thread, &reg_map);
 908          jvf != NULL;
 909          jvf = jvf->java_sender()) {
 910       if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 911         // add locked objects for this frame into list
 912         err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 913         if (err != JVMTI_ERROR_NONE) {
 914           return err;
 915         }
 916       }
 917     }
 918   }
 919 
 920   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 921   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 922   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 923   err = jmc.error();
 924 
 925   return err;
 926 }
 927 
 928 jvmtiError
 929 JvmtiEnvBase::get_owned_monitors(JavaThread* calling_thread, JavaThread* java_thread, javaVFrame* jvf,
 930                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 931   jvmtiError err = JVMTI_ERROR_NONE;
 932 #ifdef ASSERT
 933   uint32_t debug_bits = 0;
 934 #endif
 935   // assert((SafepointSynchronize::is_at_safepoint() ||
 936   //         java_thread->is_thread_fully_suspended(false, &debug_bits)),
 937   //        "at safepoint or target thread is suspended");
 938 
 939   int depth = 0;
 940   for ( ; jvf != NULL; jvf = jvf->java_sender()) {
 941     if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 942       // add locked objects for this frame into list
 943       err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 944       if (err != JVMTI_ERROR_NONE) {
 945         return err;
 946       }
 947     }
 948   }
 949 
 950   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 951   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 952   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 953   err = jmc.error();
 954 
 955   return err;
 956 }
 957 
 958 // Save JNI local handles for any objects that this frame owns.
 959 jvmtiError
 960 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
 961                                  javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, jint stack_depth) {
 962   jvmtiError err = JVMTI_ERROR_NONE;
 963   Thread* current_thread = Thread::current();
 964   ResourceMark rm(current_thread);
 965   HandleMark   hm(current_thread);
 966 
 967   GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 968   if (mons->is_empty()) {
 969     return err;  // this javaVFrame holds no monitors
 970   }
 971 
 972   oop wait_obj = NULL;
 973   {
 974     // The ObjectMonitor* can't be async deflated since we are either
 975     // at a safepoint or the calling thread is operating on itself so
 976     // it cannot leave the underlying wait() call.
 977     // Save object of current wait() call (if any) for later comparison.

1030         // already have this object so don't include it
1031         continue;
1032       }
1033     }
1034 
1035     // add the owning object to our list
1036     jvmtiMonitorStackDepthInfo *jmsdi;
1037     err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1038     if (err != JVMTI_ERROR_NONE) {
1039         return err;
1040     }
1041     Handle hobj(Thread::current(), obj);
1042     jmsdi->monitor = jni_reference(calling_thread, hobj);
1043     jmsdi->stack_depth = stack_depth;
1044     owned_monitors_list->append(jmsdi);
1045   }
1046 
1047   return err;
1048 }
1049 
1050 jvmtiError
1051 JvmtiEnvBase::get_stack_trace(javaVFrame *jvf,
1052                               jint start_depth, jint max_count,
1053                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1054   Thread *current_thread = Thread::current();
1055   ResourceMark rm(current_thread);
1056   HandleMark hm(current_thread);
1057   int count = 0;
1058 
1059   if (start_depth != 0) {
1060     if (start_depth > 0) {
1061       for (int j = 0; j < start_depth && jvf != NULL; j++) {
1062         jvf = jvf->java_sender();
1063       }
1064       if (jvf == NULL) {
1065         // start_depth is deeper than the stack depth
1066         return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1067       }
1068     } else { // start_depth < 0
1069       // we are referencing the starting depth based on the oldest
1070       // part of the stack.
1071       // optimize to limit the number of times that java_sender() is called
1072       javaVFrame *jvf_cursor = jvf;
1073       javaVFrame *jvf_prev = NULL;
1074       javaVFrame *jvf_prev_prev = NULL;
1075       int j = 0;
1076       while (jvf_cursor != NULL) {
1077         jvf_prev_prev = jvf_prev;
1078         jvf_prev = jvf_cursor;
1079         for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
1080           jvf_cursor = jvf_cursor->java_sender();
1081         }
1082       }
1083       if (j == start_depth) {
1084         // previous pointer is exactly where we want to start
1085         jvf = jvf_prev;
1086       } else {
1087         // we need to back up further to get to the right place
1088         if (jvf_prev_prev == NULL) {
1089           // the -start_depth is greater than the stack depth
1090           return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1091         }
1092         // j now is the number of frames on the stack starting with
1093         // jvf_prev, we start from jvf_prev_prev and move older on
1094         // the stack that many, the result is -start_depth frames
1095         // remaining.
1096         jvf = jvf_prev_prev;
1097         for (; j < 0; j++) {
1098           jvf = jvf->java_sender();
1099         }
1100       }
1101     }
1102   }
1103   for (; count < max_count && jvf != NULL; count++) {
1104     frame_buffer[count].method = jvf->method()->jmethod_id();
1105     frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
1106     jvf = jvf->java_sender();
1107   }
1108   *count_ptr = count;
1109   return JVMTI_ERROR_NONE;
1110 }
1111 
1112 jvmtiError
1113 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
1114                               jint start_depth, jint max_count,
1115                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1116 #ifdef ASSERT
1117   uint32_t debug_bits = 0;
1118 #endif
1119   Thread *current_thread = Thread::current();
1120   assert(SafepointSynchronize::is_at_safepoint() ||
1121          java_thread->is_handshake_safe_for(current_thread),
1122          "call by myself / at safepoint / at handshake");
1123   int count = 0;
1124   jvmtiError err = JVMTI_ERROR_NONE;
1125 
1126   if (java_thread->has_last_Java_frame()) {
1127     RegisterMap reg_map(java_thread, true, true);
1128     ResourceMark rm(current_thread);
1129     javaVFrame *jvf = get_last_java_vframe(java_thread, &reg_map);
1130 
1131     err = get_stack_trace(jvf, start_depth, max_count, frame_buffer, count_ptr);
















































1132   } else {
1133     *count_ptr = 0;
1134     if (start_depth != 0) {
1135       // no frames and there is a starting depth
1136       err = JVMTI_ERROR_ILLEGAL_ARGUMENT;
1137     }
1138   }
1139   return err;
1140 }
1141 
1142 jint
1143 JvmtiEnvBase::get_frame_count(javaVFrame *jvf) {
1144   int count = 0;
1145 
1146   while (jvf != NULL) {
1147     Method* method = jvf->method();
1148     jvf = jvf->java_sender();
1149     count++;
1150   }
1151   return count;
1152 }
1153 
1154 jvmtiError
1155 JvmtiEnvBase::get_frame_count(JavaThread* jt, jint *count_ptr) {
1156   Thread *current_thread = Thread::current();
1157   assert(current_thread == jt ||
1158          SafepointSynchronize::is_at_safepoint() ||
1159          jt->is_handshake_safe_for(current_thread),
1160          "call by myself / at safepoint / at handshake");
1161 
1162   if (!jt->has_last_Java_frame()) { // no Java frames
1163     *count_ptr = 0;
1164   } else {
1165     ResourceMark rm(current_thread);
1166     RegisterMap reg_map(jt, true, true);
1167     javaVFrame *jvf = get_last_java_vframe(jt, &reg_map);
1168 
1169     *count_ptr = get_frame_count(jvf);
1170   }
1171   return JVMTI_ERROR_NONE;
1172 }
1173 
1174 jvmtiError
1175 JvmtiEnvBase::get_frame_count(oop vthread_oop, jint *count_ptr) {
1176   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1177     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1178   }
1179   Thread *current_thread = Thread::current();
1180   ResourceMark rm(current_thread);
1181   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1182 
1183   *count_ptr = get_frame_count(jvf);
1184   return JVMTI_ERROR_NONE;
1185 }
1186 
1187 jvmtiError
1188 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
1189                                  jmethodID* method_ptr, jlocation* location_ptr) {



1190   Thread* current_thread = Thread::current();
1191   assert(java_thread->is_handshake_safe_for(current_thread),
1192          "call by myself or at handshake");
1193   ResourceMark rm(current_thread);
1194 
1195   vframe *vf = vframeForNoProcess(java_thread, depth, true /* for cont */);
1196   if (vf == NULL) {
1197     return JVMTI_ERROR_NO_MORE_FRAMES;
1198   }
1199 
1200   // vframeFor should return a java frame. If it doesn't
1201   // it means we've got an internal error and we return the
1202   // error in product mode. In debug mode we will instead
1203   // attempt to cast the vframe to a javaVFrame and will
1204   // cause an assertion/crash to allow further diagnosis.
1205 #ifdef PRODUCT
1206   if (!vf->is_java_frame()) {
1207     return JVMTI_ERROR_INTERNAL;
1208   }
1209 #endif
1210 
1211   HandleMark hm(current_thread);
1212   javaVFrame *jvf = javaVFrame::cast(vf);
1213   Method* method = jvf->method();
1214   if (method->is_native()) {
1215     *location_ptr = -1;
1216   } else {
1217     *location_ptr = jvf->bci();
1218   }
1219   *method_ptr = method->jmethod_id();
1220 
1221   return JVMTI_ERROR_NONE;
1222 }
1223 
1224 jvmtiError
1225 JvmtiEnvBase::get_frame_location(oop vthread_oop, jint depth,
1226                                  jmethodID* method_ptr, jlocation* location_ptr) {
1227   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1228     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1229   }
1230   Thread* cur_thread = Thread::current();
1231   ResourceMark rm(cur_thread);
1232   HandleMark hm(cur_thread);
1233   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1234   int cur_depth = 0;
1235 
1236   while (jvf != NULL && cur_depth < depth) {
1237     Method* method = jvf->method();
1238     jvf = jvf->java_sender();
1239     cur_depth++;
1240   }
1241   assert(depth >= cur_depth, "ran out of frames too soon");
1242   if (jvf == NULL) {
1243     return JVMTI_ERROR_NO_MORE_FRAMES;
1244   }
1245   Method* method = jvf->method();
1246   if (method->is_native()) {
1247     *location_ptr = -1;
1248   } else {
1249     *location_ptr = jvf->bci();
1250   }
1251   *method_ptr = method->jmethod_id();
1252 
1253   return JVMTI_ERROR_NONE;
1254 }
1255 
1256 bool
1257 JvmtiEnvBase::cthread_with_mounted_vthread(JavaThread* jt) {
1258   oop thread_oop = jt->threadObj();
1259   assert(thread_oop != NULL, "sanity check");
1260   oop mounted_vt = jt->mounted_vthread();
1261 
1262   return (mounted_vt != NULL && mounted_vt != thread_oop);
1263 }
1264 
1265 bool
1266 JvmtiEnvBase::cthread_with_continuation(JavaThread* jt) {
1267   ContinuationEntry* cont = NULL;
1268   if (jt->has_last_Java_frame()) {
1269     cont = jt->last_continuation(java_lang_VirtualThread::vthread_scope());
1270   }
1271   return (cont != NULL && cthread_with_mounted_vthread(jt));
1272 }
1273 
1274 jvmtiError
1275 JvmtiEnvBase::get_threadOop_and_JavaThread(ThreadsList* t_list, jthread thread,
1276                                            JavaThread** jt_pp, oop* thread_oop_p) {
1277   JavaThread* cur_thread = JavaThread::current();
1278   JavaThread* java_thread = NULL;
1279   oop thread_oop = NULL;
1280 
1281   if (thread == NULL) {
1282     java_thread = cur_thread;
1283     thread_oop = get_vthread_or_thread_oop(java_thread);
1284     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::Thread_klass())) {
1285       return JVMTI_ERROR_INVALID_THREAD;
1286     }
1287   } else {
1288     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(t_list, thread, &java_thread, &thread_oop);
1289     if (err != JVMTI_ERROR_NONE) {
1290       // We got an error code so we don't have a JavaThread*, but only return
1291       // an error from here if we didn't get a valid thread_oop. In a vthread case
1292       // the cv_external_thread_to_JavaThread is expected to correctly set the
1293       // thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1294       if (thread_oop == NULL || err != JVMTI_ERROR_INVALID_THREAD) {
1295         return err;
1296       }
1297     }
1298     if (java_thread == NULL && java_lang_VirtualThread::is_instance(thread_oop)) {
1299       oop cont = java_lang_VirtualThread::continuation(thread_oop);
1300       if (jdk_internal_vm_Continuation::is_mounted(cont)) {
1301         oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_oop);
1302         // Returned carrier_thread can be NULL for a mounted continuation.
1303         if (carrier_thread != NULL) {
1304           java_thread = java_lang_Thread::thread(carrier_thread);
1305         }
1306       }
1307     }
1308   }
1309   *jt_pp = java_thread;
1310   *thread_oop_p = thread_oop;
1311   return JVMTI_ERROR_NONE;
1312 }
1313 
1314 jvmtiError
1315 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
1316   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1317   Thread* current_thread = VMThread::vm_thread();
1318   assert(current_thread == Thread::current(), "must be");
1319 
1320   HandleMark hm(current_thread);
1321   Handle hobj;
1322 
1323   // Check arguments
1324   {
1325     oop mirror = JNIHandles::resolve_external_guard(object);
1326     NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
1327     NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
1328 
1329     hobj = Handle(current_thread, mirror);
1330   }
1331 
1332   ThreadsListHandle tlh(current_thread);

1351         }
1352         // implied else: no owner
1353       } else {
1354         // this object has a heavyweight monitor
1355         mon = mark.monitor();
1356 
1357         // The owner field of a heavyweight monitor may be NULL for no
1358         // owner, a JavaThread * or it may still be the address of the
1359         // Lock word in a JavaThread's stack. A monitor can be inflated
1360         // by a non-owning JavaThread, but only the owning JavaThread
1361         // can change the owner field from the Lock word to the
1362         // JavaThread * and it may not have done that yet.
1363         owner = (address)mon->owner();
1364       }
1365     }
1366 
1367     if (owner != NULL) {
1368       // This monitor is owned so we have to find the owning JavaThread.
1369       owning_thread = Threads::owning_thread_from_monitor_owner(tlh.list(), owner);
1370       assert(owning_thread != NULL, "owning JavaThread must not be NULL");
1371       Handle     th(current_thread, get_vthread_or_thread_oop(owning_thread));
1372       ret.owner = (jthread)jni_reference(calling_thread, th);
1373     }
1374 
1375     if (owning_thread != NULL) {  // monitor is owned
1376       // The recursions field of a monitor does not reflect recursions
1377       // as lightweight locks before inflating the monitor are not included.
1378       // We have to count the number of recursive monitor entries the hard way.
1379       // We pass a handle to survive any GCs along the way.
1380       ret.entry_count = count_locked_objects(owning_thread, hobj);
1381     }
1382     // implied else: entry_count == 0
1383   }
1384 
1385   jint nWant = 0, nWait = 0;
1386   if (mon != NULL) {
1387     // this object has a heavyweight monitor
1388     nWant = mon->contentions(); // # of threads contending for monitor
1389     nWait = mon->waiters();     // # of threads in Object.wait()
1390     ret.waiter_count = nWant + nWait;
1391     ret.notify_waiter_count = nWait;

1414 
1415     // Number of waiters may actually be less than the waiter count.
1416     // So NULL out memory so that unused memory will be NULL.
1417     memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1418     memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1419 
1420     if (ret.waiter_count > 0) {
1421       // we have contending and/or waiting threads
1422       if (nWant > 0) {
1423         // we have contending threads
1424         ResourceMark rm(current_thread);
1425         // get_pending_threads returns only java thread so we do not need to
1426         // check for non java threads.
1427         GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(tlh.list(), nWant, (address)mon);
1428         if (wantList->length() < nWant) {
1429           // robustness: the pending list has gotten smaller
1430           nWant = wantList->length();
1431         }
1432         for (int i = 0; i < nWant; i++) {
1433           JavaThread *pending_thread = wantList->at(i);
1434           Handle th(current_thread, get_vthread_or_thread_oop(pending_thread));
1435           ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1436         }
1437       }
1438       if (nWait > 0) {
1439         // we have threads in Object.wait()
1440         int offset = nWant;  // add after any contending threads
1441         ObjectWaiter *waiter = mon->first_waiter();
1442         for (int i = 0, j = 0; i < nWait; i++) {
1443           if (waiter == NULL) {
1444             // robustness: the waiting list has gotten smaller
1445             nWait = j;
1446             break;
1447           }
1448           JavaThread *w = mon->thread_of_waiter(waiter);
1449           if (w != NULL) {
1450             // If the thread was found on the ObjectWaiter list, then
1451             // it has not been notified. This thread can't change the
1452             // state of the monitor so it doesn't need to be suspended.
1453             Handle th(current_thread, get_vthread_or_thread_oop(w));
1454             ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1455             ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1456           }
1457           waiter = mon->next_waiter(waiter);
1458         }
1459       }
1460     } // ThreadsListHandle is destroyed here.
1461 
1462     // Adjust count. nWant and nWait count values may be less than original.
1463     ret.waiter_count = nWant + nWait;
1464     ret.notify_waiter_count = nWait;
1465   } else {
1466     // this object has a lightweight monitor and we have nothing more
1467     // to do here because the defaults are just fine.
1468   }
1469 
1470   // we don't update return parameter unless everything worked
1471   *info_ptr = ret;
1472 
1473   return JVMTI_ERROR_NONE;
1474 }
1475 
1476 jvmtiError
1477 JvmtiEnvBase::check_thread_list(jint count, const jthread* list) {
1478   if (list == NULL && count != 0) {
1479     return JVMTI_ERROR_NULL_POINTER;
1480   }
1481   for (int i = 0; i < count; i++) {
1482     jthread thread = list[i];
1483     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1484     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::VirtualThread_klass())) {
1485       return JVMTI_ERROR_INVALID_THREAD;
1486     }
1487   }
1488   return JVMTI_ERROR_NONE;
1489 }
1490 
1491 bool
1492 JvmtiEnvBase::is_in_thread_list(jint count, const jthread* list, oop jt_oop) {
1493   for (int idx = 0; idx < count; idx++) {
1494     jthread thread = list[idx];
1495     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1496     if (thread_oop == jt_oop) {
1497       return true;
1498     }
1499   }
1500   return false;
1501 }
1502 
1503 jvmtiError
1504 JvmtiEnvBase::suspend_thread(oop thread_oop, JavaThread* java_thread, bool single_suspend,
1505                              int* need_safepoint_p) {
1506   JavaThread* current = JavaThread::current();
1507   HandleMark hm(current);
1508   Handle thread_h(current, thread_oop);
1509   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1510 
1511   if (is_virtual) {
1512     if (single_suspend) {
1513       if (JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1514         return JVMTI_ERROR_THREAD_SUSPENDED;
1515       }
1516       JvmtiVTSuspender::register_vthread_suspend(thread_h());
1517       // Check if virtual thread is mounted and there is a java_thread.
1518       // A non-NULL java_thread is always passed in the !single_suspend case.
1519       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1520       java_thread = carrier_thread == NULL ? NULL : java_lang_Thread::thread(carrier_thread);
1521     }
1522     // The java_thread can be still blocked in VTMT transition after a previous JVMTI resume call.
1523     // There is no need to suspend the java_thread in this case. After vthread unblocking,
1524     // it will check for ext_suspend request and suspend itself if necessary.
1525     if (java_thread == NULL || java_thread->is_suspended()) {
1526       // We are done if the virtual thread is unmounted or
1527       // the java_thread is externally suspended.
1528       return JVMTI_ERROR_NONE;
1529     }
1530     // The virtual thread is mounted: suspend the java_thread.
1531   }
1532   // Don't allow hidden thread suspend request.
1533   if (java_thread->is_hidden_from_external_view()) {
1534     return JVMTI_ERROR_NONE;
1535   }
1536   // A case of non-virtual thread.
1537   if (!is_virtual) {
1538     // Thread.suspend() is used in some tests. It sets jt->is_suspended() only.
1539     if (java_thread->is_thread_suspended() ||
1540         (thread_h() == java_thread->vthread() && java_thread->is_suspended())) {
1541       return JVMTI_ERROR_THREAD_SUSPENDED;
1542     }
1543     java_thread->set_thread_suspended();
1544   }
1545   assert(JvmtiVTMTDisabler::VTMT_count() == 0, "must be 0");
1546   assert(!java_thread->is_in_VTMT(), "sanity check");
1547 
1548   if (java_thread == current) {
1549     // java_thread will be suspended in the ~JvmtiVTMTDisabler.
1550     return JVMTI_ERROR_NONE;
1551   }
1552   assert(!single_suspend || (!is_virtual && java_thread->is_thread_suspended()) ||
1553           (is_virtual && JvmtiVTSuspender::is_vthread_suspended(thread_h())),
1554          "sanity check");
1555 
1556   if (is_virtual || thread_h() == java_thread->vthread()) {
1557     assert(single_suspend || is_virtual, "SuspendAllVirtualThreads should never suspend non-virtual threads");
1558     // Case of mounted virtual or attached carrier thread.
1559     if (!JvmtiSuspendControl::suspend(java_thread)) {
1560       // Thread is already suspended or in process of exiting.
1561       if (java_thread->is_exiting()) {
1562         // The thread was in the process of exiting.
1563         return JVMTI_ERROR_THREAD_NOT_ALIVE;
1564       }
1565     }
1566   }
1567   return JVMTI_ERROR_NONE;
1568 }
1569 
1570 jvmtiError
1571 JvmtiEnvBase::resume_thread(oop thread_oop, JavaThread* java_thread, bool single_suspend) {
1572   JavaThread* current = JavaThread::current();
1573   HandleMark hm(current);
1574   Handle thread_h(current, thread_oop);
1575   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1576 
1577   if (is_virtual) {
1578     if (single_suspend) {
1579       if (!JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1580         return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1581       }
1582       JvmtiVTSuspender::register_vthread_resume(thread_h());
1583       // Check if virtual thread is mounted and there is a java_thread.
1584       // A non-NULL java_thread is always passed in the !single_suspend case.
1585       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1586       java_thread = carrier_thread == NULL ? NULL : java_lang_Thread::thread(carrier_thread);
1587     }
1588     // The java_thread can be still blocked in VTMT transition after a previous JVMTI suspend call.
1589     // There is no need to resume the java_thread in this case. After vthread unblocking,
1590     // it will check for is_vthread_suspended request and remain resumed if necessary.
1591     if (java_thread == NULL || !java_thread->is_suspended()) {
1592       // We are done if the virtual thread is unmounted or
1593       // the java_thread is not externally suspended.
1594       return JVMTI_ERROR_NONE;
1595     }
1596     // The virtual thread is mounted and java_thread is supended: resume the java_thread.
1597   }
1598   // Don't allow hidden thread resume request.
1599   if (java_thread->is_hidden_from_external_view()) {
1600     return JVMTI_ERROR_NONE;
1601   }
1602   // A case of a non-virtual thread.
1603   if (!is_virtual) {
1604     if (!java_thread->is_thread_suspended() &&
1605         (thread_h() == java_thread->vthread() && !java_thread->is_suspended())) {
1606       return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1607     }
1608     java_thread->clear_thread_suspended();
1609   }
1610   assert(!java_thread->is_in_VTMT(), "sanity check");
1611   if (is_virtual || thread_h() == java_thread->vthread()) {
1612     assert(single_suspend || is_virtual, "ResumeAllVirtualThreads should never resume non-virtual threads");
1613     if (java_thread->is_suspended()) {
1614       if (!JvmtiSuspendControl::resume(java_thread)) {
1615         return JVMTI_ERROR_INTERNAL;
1616       }
1617     }
1618   }
1619   return JVMTI_ERROR_NONE;
1620 }
1621 
1622 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1623   _env = env;
1624   _allocations = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<unsigned char*>(20, mtServiceability);
1625   _failed = false;
1626 }
1627 ResourceTracker::~ResourceTracker() {
1628   if (_failed) {
1629     for (int i=0; i<_allocations->length(); i++) {
1630       _env->deallocate(_allocations->at(i));
1631     }
1632   }
1633   delete _allocations;
1634 }
1635 
1636 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1637   unsigned char *ptr;
1638   jvmtiError err = _env->allocate(size, &ptr);
1639   if (err == JVMTI_ERROR_NONE) {
1640     _allocations->append(ptr);
1641     *mem_ptr = ptr;

1648 
1649 unsigned char* ResourceTracker::allocate(jlong size) {
1650   unsigned char* ptr;
1651   allocate(size, &ptr);
1652   return ptr;
1653 }
1654 
1655 char* ResourceTracker::strdup(const char* str) {
1656   char *dup_str = (char*)allocate(strlen(str)+1);
1657   if (dup_str != NULL) {
1658     strcpy(dup_str, str);
1659   }
1660   return dup_str;
1661 }
1662 
1663 struct StackInfoNode {
1664   struct StackInfoNode *next;
1665   jvmtiStackInfo info;
1666 };
1667 
1668 
1669 // Create a jvmtiStackInfo inside a linked list node and create a
1670 // buffer for the frame information, both allocated as resource objects.
1671 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1672 // Note that either or both of thr and thread_oop
1673 // may be null if the thread is new or has exited.
1674 void
1675 MultipleStackTracesCollector::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1676 #ifdef ASSERT
1677   Thread *current_thread = Thread::current();
1678   assert(SafepointSynchronize::is_at_safepoint() ||
1679          thr == NULL ||
1680          thr->is_handshake_safe_for(current_thread),
1681          "unmounted virtual thread / call by myself / at safepoint / at handshake");
1682 #endif
1683 
1684   jint state = 0;
1685   struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
1686   jvmtiStackInfo *infop = &(node->info);
1687 
1688   node->next = head();
1689   set_head(node);
1690   infop->frame_count = 0;
1691   infop->frame_buffer = NULL;
1692   infop->thread = jt;
1693 
1694   // Support for virtual threads
1695   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1696     state = JvmtiEnvBase::get_vthread_state(thread_oop);

1697 
1698     if ((state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1699       javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(thread_oop);
1700       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1701       _result = env()->get_stack_trace(jvf, 0, max_frame_count(),
1702                                      infop->frame_buffer, &(infop->frame_count));





1703     }







1704   } else {
1705     state = JvmtiEnvBase::get_thread_state(thread_oop, thr);
1706     if (thr != NULL && (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1707       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1708       _result = env()->get_stack_trace(thr, 0, max_frame_count(),
1709                                        infop->frame_buffer, &(infop->frame_count));
1710     }
1711   }
1712   _frame_count_total += infop->frame_count;
1713   infop->state = state;
1714 }
1715 
1716 // Based on the stack information in the linked list, allocate memory
1717 // block to return and fill it from the info in the linked list.
1718 void
1719 MultipleStackTracesCollector::allocate_and_fill_stacks(jint thread_count) {
1720   // do I need to worry about alignment issues?
1721   jlong alloc_size =  thread_count       * sizeof(jvmtiStackInfo)
1722                     + _frame_count_total * sizeof(jvmtiFrameInfo);
1723   env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1724 
1725   // pointers to move through the newly allocated space as it is filled in
1726   jvmtiStackInfo *si = _stack_info + thread_count;      // bottom of stack info
1727   jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si;            // is the top of frame info
1728 
1729   // copy information in resource area into allocated buffer
1730   // insert stack info backwards since linked list is backwards
1731   // insert frame info forwards
1732   // walk the StackInfoNodes
1733   for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {

1747   assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1748          "the last copied frame info must be the last record");
1749 }
1750 
1751 
1752 void
1753 VM_GetThreadListStackTraces::doit() {
1754   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1755 
1756   ResourceMark rm;
1757   ThreadsListHandle tlh;
1758   for (int i = 0; i < _thread_count; ++i) {
1759     jthread jt = _thread_list[i];
1760     JavaThread* java_thread = NULL;
1761     oop thread_oop = NULL;
1762     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), jt, &java_thread, &thread_oop);
1763     if (err != JVMTI_ERROR_NONE) {
1764       // We got an error code so we don't have a JavaThread *, but
1765       // only return an error from here if we didn't get a valid
1766       // thread_oop.
1767       // In the virtual thread case the cv_external_thread_to_JavaThread is expected to correctly set
1768       // the thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1769       if (thread_oop == NULL) {
1770         _collector.set_result(err);
1771         return;
1772       }
1773       // We have a valid thread_oop.
1774     }
1775     _collector.fill_frames(jt, java_thread, thread_oop);
1776   }
1777   _collector.allocate_and_fill_stacks(_thread_count);
1778 }
1779 
1780 void
1781 GetSingleStackTraceClosure::do_thread(Thread *target) {
1782     JavaThread *jt = JavaThread::cast(target);
1783     oop thread_oop = jt->threadObj();
1784 
1785     if (!jt->is_exiting() && thread_oop != NULL) {
1786         ResourceMark rm;
1787         _collector.fill_frames(_jthread, jt, thread_oop);
1788         _collector.allocate_and_fill_stacks(1);
1789     }
1790 }
1791 
1792 void
1793 VM_GetAllStackTraces::doit() {
1794   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1795 
1796   ResourceMark rm;
1797   _final_thread_count = 0;
1798   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1799     oop thread_oop = jt->threadObj();
1800     if (thread_oop != NULL &&
1801         !jt->is_exiting() &&
1802         java_lang_Thread::is_alive(thread_oop) &&
1803         !jt->is_hidden_from_external_view()) {
1804       ++_final_thread_count;
1805       // Handle block of the calling thread is used to create local refs.
1806       _collector.fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
1807                              jt, thread_oop);
1808     }
1809   }

2111   // (see call_VM_base() in assembler_<cpu>.cpp).
2112 
2113   // It's fine to update the thread state here because no JVMTI events
2114   // shall be posted for this PopFrame.
2115 
2116   if (!java_thread->is_exiting() && java_thread->threadObj() != NULL) {
2117     _state->update_for_pop_top_frame();
2118     java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
2119     // Set pending step flag for this popframe and it is cleared when next
2120     // step event is posted.
2121     _state->set_pending_step_for_popframe();
2122     _result = JVMTI_ERROR_NONE;
2123   }
2124 }
2125 
2126 void
2127 SetFramePopClosure::doit(Thread *target, bool self) {
2128   ResourceMark rm;
2129   JavaThread* java_thread = JavaThread::cast(target);
2130 
2131   // TBD: This might need to be corrected for detached carrier and virtual threads.
2132   assert(_state->get_thread_or_saved() == java_thread, "Must be");
2133 
2134   if (!self && !java_thread->is_suspended()) {
2135     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2136     return;
2137   }
2138 
2139   vframe *vf = JvmtiEnvBase::vframeForNoProcess(java_thread, _depth);
2140   if (vf == NULL) {
2141     _result = JVMTI_ERROR_NO_MORE_FRAMES;
2142     return;
2143   }
2144   vf = JvmtiEnvBase::check_and_skip_hidden_frames(java_thread, (javaVFrame*)vf);
2145   if (!vf->is_java_frame() || ((javaVFrame*) vf)->method()->is_native()) {
2146     _result = JVMTI_ERROR_OPAQUE_FRAME;
2147     return;
2148   }
2149 
2150   assert(vf->frame_pointer() != NULL, "frame pointer mustn't be NULL");
2151   if (java_thread->is_exiting() || java_thread->threadObj() == NULL) {
2152     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2153   }
2154   int frame_number = _state->count_frames() - _depth;
2155   _state->env_thread_state((JvmtiEnvBase*)_env)->set_frame_pop(frame_number);
2156   _result = JVMTI_ERROR_NONE;
2157 }
2158 
2159 void
2160 GetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2161   JavaThread *jt = JavaThread::cast(target);
2162   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
2163     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread,
2164                                                          jt,
2165                                                          _owned_monitors_list);
2166   }
2167 }
2168 
2169 void
2170 GetCurrentContendedMonitorClosure::do_thread(Thread *target) {
2171   JavaThread *jt = JavaThread::cast(target);
2172   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
2173     _result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor(_calling_thread,
2174                                                                     jt,
2175                                                                     _owned_monitor_ptr);
2176   }
2177 }
2178 
2179 void
2180 VM_VThreadGetStackTrace::doit() {
2181   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2182     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2183     return;
2184   }
2185   ResourceMark rm;
2186   javaVFrame* jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2187 
2188   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2189                                                     _start_depth, _max_count,
2190                                                     _frame_buffer, _count_ptr);
2191 }
2192 
2193 void
2194 GetStackTraceClosure::do_thread(Thread *target) {
2195   JavaThread *jt = JavaThread::cast(target);
2196   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2197     _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jt,
2198                                                       _start_depth, _max_count,
2199                                                       _frame_buffer, _count_ptr);
2200   }
2201 }
2202 
2203 #ifdef ASSERT
2204 void
2205 PrintStackTraceClosure::do_thread_impl(Thread *target) {
2206   JavaThread *java_thread = JavaThread::cast(target);
2207   Thread *current_thread = Thread::current();
2208 
2209   ResourceMark rm (current_thread);
2210   const char* tname = JvmtiTrace::safe_get_thread_name(java_thread);
2211   oop t_oop = java_thread->mounted_vthread();
2212   t_oop = t_oop == NULL ? java_thread->threadObj() : t_oop;
2213   bool is_vt_suspended = java_lang_VirtualThread::is_instance(t_oop) && JvmtiVTSuspender::is_vthread_suspended(t_oop);
2214 
2215   tty->print_cr("%s(%s) exiting: %d is_susp: %d is_thread_susp: %d is_vthread_susp: %d is_VTMT_disabler: %d, is_in_VTMT = %d",
2216                 tname, java_thread->name(), java_thread->is_exiting(),
2217                 java_thread->is_suspended(), java_thread->is_thread_suspended(), is_vt_suspended,
2218                 java_thread->is_VTMT_disabler(), java_thread->is_in_VTMT());
2219 
2220   if (java_thread->has_last_Java_frame()) {
2221     RegisterMap reg_map(java_thread, true, true);
2222     ResourceMark rm(current_thread);
2223     HandleMark hm(current_thread);
2224     javaVFrame *jvf = JvmtiEnvBase::get_last_java_vframe(java_thread, &reg_map);
2225     while (jvf != NULL) {
2226       tty->print_cr("  %s:%d",
2227                     jvf->method()->external_name(),
2228                     jvf->method()->line_number_from_bci(jvf->bci()));
2229       jvf = jvf->java_sender();
2230     }
2231   }
2232   tty->print_cr("");
2233 }
2234 
2235 void
2236 PrintStackTraceClosure::do_thread(Thread *target) {
2237   JavaThread *java_thread = JavaThread::cast(target);
2238   Thread *current_thread = Thread::current();
2239 
2240   assert(SafepointSynchronize::is_at_safepoint() ||
2241       java_thread->is_handshake_safe_for(current_thread),
2242          "call by myself / at safepoint / at handshake");
2243 
2244   PrintStackTraceClosure::do_thread_impl(target);
2245 }
2246 #endif
2247 
2248 void
2249 VM_VThreadGetFrameCount::doit() {
2250   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2251 }
2252 
2253 void
2254 GetFrameCountClosure::do_thread(Thread *target) {
2255   JavaThread* jt = JavaThread::cast(target);
2256   assert(target == jt, "just checking");
2257   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2258     _result = ((JvmtiEnvBase*)_env)->get_frame_count(jt, _count_ptr);
2259   }
2260 }
2261 
2262 void
2263 GetFrameLocationClosure::do_thread(Thread *target) {
2264   JavaThread *jt = JavaThread::cast(target);
2265   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2266     _result = ((JvmtiEnvBase*)_env)->get_frame_location(jt, _depth,
2267                                                         _method_ptr, _location_ptr);
2268   }
2269 }
2270 
2271 void
2272 VThreadGetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2273   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2274     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2275     return;
2276   }
2277   JavaThread* java_thread = JavaThread::cast(target);
2278   Thread* cur_thread = Thread::current();
2279   ResourceMark rm(cur_thread);
2280   HandleMark hm(cur_thread);
2281 
2282   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2283 
2284   if (!java_thread->is_exiting() && java_thread->threadObj() != NULL) {
2285     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors((JavaThread*)target,
2286                                                          java_thread,
2287                                                          jvf,
2288                                                          _owned_monitors_list);
2289   }
2290 }
2291 
2292 void
2293 VThreadGetCurrentContendedMonitorClosure::do_thread(Thread *target) {
2294   JavaThread* java_thread = JavaThread::cast(target);
2295 
2296   if (!java_thread->is_exiting() && java_thread->threadObj() != NULL) {
2297     _result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor((JavaThread*)target,
2298                                                                     java_thread,
2299                                                                     _owned_monitor_ptr);
2300   }
2301 }
2302 
2303 void
2304 VThreadGetThreadClosure::do_thread(Thread *target) {
2305   oop carrier_thread = java_lang_VirtualThread::carrier_thread(_vthread_h());
2306   *_carrier_thread_ptr = (jthread)JNIHandles::make_local(target, carrier_thread);}
2307 
2308 void
2309 VThreadGetStackTraceClosure::do_thread(Thread *target) {
2310   assert(target->is_Java_thread(), "just checking");
2311   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2312     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2313     return;
2314   }
2315   Thread* cur_thread = Thread::current();
2316   ResourceMark rm(cur_thread);
2317   HandleMark hm(cur_thread);
2318 
2319   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2320   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2321                                                     _start_depth, _max_count,
2322                                                     _frame_buffer, _count_ptr);
2323 }
2324 
2325 void
2326 VThreadGetFrameCountClosure::do_thread(Thread *target) {
2327   assert(target->is_Java_thread(), "just checking");
2328   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2329 }
2330 
2331 void
2332 VThreadGetFrameLocationClosure::do_thread(Thread *target) {
2333   assert(target->is_Java_thread(), "just checking");
2334   _result = ((JvmtiEnvBase*)_env)->get_frame_location(_vthread_h(), _depth,
2335                                                       _method_ptr, _location_ptr);
2336 }
2337 
2338 void
2339 VThreadGetThreadStateClosure::do_thread(Thread *target) {
2340   assert(target->is_Java_thread(), "just checking");
2341   jshort vthread_state = java_lang_VirtualThread::state(_vthread_h());
2342   oop carrier_thread_oop = java_lang_VirtualThread::carrier_thread(_vthread_h());
2343   jint state;
2344 
2345   if (vthread_state == java_lang_VirtualThread::RUNNING && carrier_thread_oop != NULL) {
2346     state = (jint) java_lang_Thread::get_thread_status(carrier_thread_oop);
2347     JavaThread* java_thread = java_lang_Thread::thread(carrier_thread_oop);
2348     if (java_thread->is_suspended()) {
2349       state |= JVMTI_THREAD_STATE_SUSPENDED;
2350     }
2351   } else {
2352     state = (jint) java_lang_VirtualThread::map_state_to_thread_status(vthread_state);
2353   }
2354   if (java_lang_Thread::interrupted(_vthread_h())) {
2355     state |= JVMTI_THREAD_STATE_INTERRUPTED;
2356   }
2357   *_state_ptr = state;
2358   _result = JVMTI_ERROR_NONE;
2359 }
< prev index next >