1 /*
   2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoaderDataGraph.hpp"
  27 #include "classfile/javaClasses.hpp"
  28 #include "classfile/moduleEntry.hpp"
  29 #include "jvmtifiles/jvmtiEnv.hpp"
  30 #include "memory/iterator.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "oops/klass.inline.hpp"
  33 #include "oops/objArrayKlass.hpp"
  34 #include "oops/objArrayOop.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "oops/oopHandle.inline.hpp"
  37 #include "prims/jvmtiEnvBase.hpp"
  38 #include "prims/jvmtiEventController.inline.hpp"
  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 
  80 // perform initializations that must occur before any JVMTI environments
  81 // are released but which should only be initialized once (no matter
  82 // how many environments are created).
  83 void
  84 JvmtiEnvBase::globally_initialize() {
  85   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
  86   assert(_globally_initialized == false, "bad call");
  87 
  88   JvmtiManageCapabilities::initialize();
  89 
  90   // register extension functions and events
  91   JvmtiExtensions::register_extensions();
  92 
  93 #ifdef JVMTI_TRACE
  94   JvmtiTrace::initialize();
  95 #endif
  96 
  97   _globally_initialized = true;
  98 }
  99 
 100 
 101 void
 102 JvmtiEnvBase::initialize() {
 103   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 104 
 105   // Add this environment to the end of the environment list (order is important)
 106   {
 107     // This block of code must not contain any safepoints, as list deallocation
 108     // (which occurs at a safepoint) cannot occur simultaneously with this list
 109     // addition.  Note: NoSafepointVerifier cannot, currently, be used before
 110     // threads exist.
 111     JvmtiEnvIterator it;
 112     JvmtiEnvBase *previous_env = NULL;
 113     for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
 114       previous_env = env;
 115     }
 116     if (previous_env == NULL) {
 117       _head_environment = this;
 118     } else {
 119       previous_env->set_next_environment(this);
 120     }
 121   }
 122 
 123   if (_globally_initialized == false) {
 124     globally_initialize();
 125   }
 126 }
 127 
 128 jvmtiPhase
 129 JvmtiEnvBase::phase() {
 130   // For the JVMTI environments possessed the can_generate_early_vmstart:
 131   //   replace JVMTI_PHASE_PRIMORDIAL with JVMTI_PHASE_START
 132   if (_phase == JVMTI_PHASE_PRIMORDIAL &&
 133       JvmtiExport::early_vmstart_recorded() &&
 134       early_vmstart_env()) {
 135     return JVMTI_PHASE_START;
 136   }
 137   return _phase; // Normal case
 138 }
 139 
 140 bool
 141 JvmtiEnvBase::is_valid() {
 142   jint value = 0;
 143 
 144   // This object might not be a JvmtiEnvBase so we can't assume
 145   // the _magic field is properly aligned. Get the value in a safe
 146   // way and then check against JVMTI_MAGIC.
 147 
 148   switch (sizeof(_magic)) {
 149   case 2:
 150     value = Bytes::get_native_u2((address)&_magic);
 151     break;
 152 
 153   case 4:
 154     value = Bytes::get_native_u4((address)&_magic);
 155     break;
 156 
 157   case 8:
 158     value = Bytes::get_native_u8((address)&_magic);
 159     break;
 160 
 161   default:
 162     guarantee(false, "_magic field is an unexpected size");
 163   }
 164 
 165   return value == JVMTI_MAGIC;
 166 }
 167 
 168 
 169 bool
 170 JvmtiEnvBase::use_version_1_0_semantics() {
 171   int major, minor, micro;
 172 
 173   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 174   return major == 1 && minor == 0;  // micro version doesn't matter here
 175 }
 176 
 177 
 178 bool
 179 JvmtiEnvBase::use_version_1_1_semantics() {
 180   int major, minor, micro;
 181 
 182   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 183   return major == 1 && minor == 1;  // micro version doesn't matter here
 184 }
 185 
 186 bool
 187 JvmtiEnvBase::use_version_1_2_semantics() {
 188   int major, minor, micro;
 189 
 190   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 191   return major == 1 && minor == 2;  // micro version doesn't matter here
 192 }
 193 
 194 
 195 JvmtiEnvBase::JvmtiEnvBase(jint version) : _env_event_enable() {
 196   _version = version;
 197   _env_local_storage = NULL;
 198   _tag_map = NULL;
 199   _native_method_prefix_count = 0;
 200   _native_method_prefixes = NULL;
 201   _next = NULL;
 202   _class_file_load_hook_ever_enabled = false;
 203 
 204   // Moot since ClassFileLoadHook not yet enabled.
 205   // But "true" will give a more predictable ClassFileLoadHook behavior
 206   // for environment creation during ClassFileLoadHook.
 207   _is_retransformable = true;
 208 
 209   // all callbacks initially NULL
 210   memset(&_event_callbacks,0,sizeof(jvmtiEventCallbacks));
 211 
 212   // all capabilities initially off
 213   memset(&_current_capabilities, 0, sizeof(_current_capabilities));
 214 
 215   // all prohibited capabilities initially off
 216   memset(&_prohibited_capabilities, 0, sizeof(_prohibited_capabilities));
 217 
 218   _magic = JVMTI_MAGIC;
 219 
 220   JvmtiEventController::env_initialize((JvmtiEnv*)this);
 221 
 222 #ifdef JVMTI_TRACE
 223   _jvmti_external.functions = TraceJVMTI != NULL ? &jvmtiTrace_Interface : &jvmti_Interface;
 224 #else
 225   _jvmti_external.functions = &jvmti_Interface;
 226 #endif
 227 }
 228 
 229 
 230 void
 231 JvmtiEnvBase::dispose() {
 232 
 233 #ifdef JVMTI_TRACE
 234   JvmtiTrace::shutdown();
 235 #endif
 236 
 237   // Dispose of event info and let the event controller call us back
 238   // in a locked state (env_dispose, below)
 239   JvmtiEventController::env_dispose(this);
 240 }
 241 
 242 void
 243 JvmtiEnvBase::env_dispose() {
 244   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 245 
 246   // We have been entered with all events disabled on this environment.
 247   // A race to re-enable events (by setting callbacks) is prevented by
 248   // checking for a valid environment when setting callbacks (while
 249   // holding the JvmtiThreadState_lock).
 250 
 251   // Mark as invalid.
 252   _magic = DISPOSED_MAGIC;
 253 
 254   // Relinquish all capabilities.
 255   jvmtiCapabilities *caps = get_capabilities();
 256   JvmtiManageCapabilities::relinquish_capabilities(caps, caps, caps);
 257 
 258   // Same situation as with events (see above)
 259   set_native_method_prefixes(0, NULL);
 260 
 261   JvmtiTagMap* tag_map_to_clear = tag_map_acquire();
 262   // A tag map can be big, clear it now to save memory until
 263   // the destructor runs.
 264   if (tag_map_to_clear != NULL) {
 265     tag_map_to_clear->clear();
 266   }
 267 
 268   _needs_clean_up = true;
 269 }
 270 
 271 
 272 JvmtiEnvBase::~JvmtiEnvBase() {
 273   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 274 
 275   // There is a small window of time during which the tag map of a
 276   // disposed environment could have been reallocated.
 277   // Make sure it is gone.
 278   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
 279   set_tag_map(NULL);
 280   // A tag map can be big, deallocate it now
 281   if (tag_map_to_deallocate != NULL) {
 282     delete tag_map_to_deallocate;
 283   }
 284 
 285   _magic = BAD_MAGIC;
 286 }
 287 
 288 
 289 void
 290 JvmtiEnvBase::periodic_clean_up() {
 291   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 292 
 293   // JvmtiEnvBase reference is saved in JvmtiEnvThreadState. So
 294   // clean up JvmtiThreadState before deleting JvmtiEnv pointer.
 295   JvmtiThreadState::periodic_clean_up();
 296 
 297   // Unlink all invalid environments from the list of environments
 298   // and deallocate them
 299   JvmtiEnvIterator it;
 300   JvmtiEnvBase* previous_env = NULL;
 301   JvmtiEnvBase* env = it.first();
 302   while (env != NULL) {
 303     if (env->is_valid()) {
 304       previous_env = env;
 305       env = it.next(env);
 306     } else {
 307       // This one isn't valid, remove it from the list and deallocate it
 308       JvmtiEnvBase* defunct_env = env;
 309       env = it.next(env);
 310       if (previous_env == NULL) {
 311         _head_environment = env;
 312       } else {
 313         previous_env->set_next_environment(env);
 314       }
 315       delete defunct_env;
 316     }
 317   }
 318 
 319 }
 320 
 321 
 322 void
 323 JvmtiEnvBase::check_for_periodic_clean_up() {
 324   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 325 
 326   class ThreadInsideIterationClosure: public ThreadClosure {
 327    private:
 328     bool _inside;
 329    public:
 330     ThreadInsideIterationClosure() : _inside(false) {};
 331 
 332     void do_thread(Thread* thread) {
 333       _inside |= thread->is_inside_jvmti_env_iteration();
 334     }
 335 
 336     bool is_inside_jvmti_env_iteration() {
 337       return _inside;
 338     }
 339   };
 340 
 341   if (_needs_clean_up) {
 342     // Check if we are currently iterating environment,
 343     // deallocation should not occur if we are
 344     ThreadInsideIterationClosure tiic;
 345     Threads::threads_do(&tiic);
 346     if (!tiic.is_inside_jvmti_env_iteration() &&
 347              !is_inside_dying_thread_env_iteration()) {
 348       _needs_clean_up = false;
 349       JvmtiEnvBase::periodic_clean_up();
 350     }
 351   }
 352 }
 353 
 354 
 355 void
 356 JvmtiEnvBase::record_first_time_class_file_load_hook_enabled() {
 357   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
 358          "sanity check");
 359 
 360   if (!_class_file_load_hook_ever_enabled) {
 361     _class_file_load_hook_ever_enabled = true;
 362 
 363     if (get_capabilities()->can_retransform_classes) {
 364       _is_retransformable = true;
 365     } else {
 366       _is_retransformable = false;
 367 
 368       // cannot add retransform capability after ClassFileLoadHook has been enabled
 369       get_prohibited_capabilities()->can_retransform_classes = 1;
 370     }
 371   }
 372 }
 373 
 374 
 375 void
 376 JvmtiEnvBase::record_class_file_load_hook_enabled() {
 377   if (!_class_file_load_hook_ever_enabled) {
 378     if (Threads::number_of_threads() == 0) {
 379       record_first_time_class_file_load_hook_enabled();
 380     } else {
 381       MutexLocker mu(JvmtiThreadState_lock);
 382       record_first_time_class_file_load_hook_enabled();
 383     }
 384   }
 385 }
 386 
 387 
 388 jvmtiError
 389 JvmtiEnvBase::set_native_method_prefixes(jint prefix_count, char** prefixes) {
 390   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
 391          "sanity check");
 392 
 393   int old_prefix_count = get_native_method_prefix_count();
 394   char **old_prefixes = get_native_method_prefixes();
 395 
 396   // allocate and install the new prefixex
 397   if (prefix_count == 0 || !is_valid()) {
 398     _native_method_prefix_count = 0;
 399     _native_method_prefixes = NULL;
 400   } else {
 401     // there are prefixes, allocate an array to hold them, and fill it
 402     char** new_prefixes = (char**)os::malloc((prefix_count) * sizeof(char*), mtInternal);
 403     if (new_prefixes == NULL) {
 404       return JVMTI_ERROR_OUT_OF_MEMORY;
 405     }
 406     for (int i = 0; i < prefix_count; i++) {
 407       char* prefix = prefixes[i];
 408       if (prefix == NULL) {
 409         for (int j = 0; j < (i-1); j++) {
 410           os::free(new_prefixes[j]);
 411         }
 412         os::free(new_prefixes);
 413         return JVMTI_ERROR_NULL_POINTER;
 414       }
 415       prefix = os::strdup(prefixes[i]);
 416       if (prefix == NULL) {
 417         for (int j = 0; j < (i-1); j++) {
 418           os::free(new_prefixes[j]);
 419         }
 420         os::free(new_prefixes);
 421         return JVMTI_ERROR_OUT_OF_MEMORY;
 422       }
 423       new_prefixes[i] = prefix;
 424     }
 425     _native_method_prefix_count = prefix_count;
 426     _native_method_prefixes = new_prefixes;
 427   }
 428 
 429   // now that we know the new prefixes have been successfully installed we can
 430   // safely remove the old ones
 431   if (old_prefix_count != 0) {
 432     for (int i = 0; i < old_prefix_count; i++) {
 433       os::free(old_prefixes[i]);
 434     }
 435     os::free(old_prefixes);
 436   }
 437 
 438   return JVMTI_ERROR_NONE;
 439 }
 440 
 441 
 442 // Collect all the prefixes which have been set in any JVM TI environments
 443 // by the SetNativeMethodPrefix(es) functions.  Be sure to maintain the
 444 // order of environments and the order of prefixes within each environment.
 445 // Return in a resource allocated array.
 446 char**
 447 JvmtiEnvBase::get_all_native_method_prefixes(int* count_ptr) {
 448   assert(Threads::number_of_threads() == 0 ||
 449          SafepointSynchronize::is_at_safepoint() ||
 450          JvmtiThreadState_lock->is_locked(),
 451          "sanity check");
 452 
 453   int total_count = 0;
 454   GrowableArray<char*>* prefix_array =new GrowableArray<char*>(5);
 455 
 456   JvmtiEnvIterator it;
 457   for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
 458     int prefix_count = env->get_native_method_prefix_count();
 459     char** prefixes = env->get_native_method_prefixes();
 460     for (int j = 0; j < prefix_count; j++) {
 461       // retrieve a prefix and so that it is safe against asynchronous changes
 462       // copy it into the resource area
 463       char* prefix = prefixes[j];
 464       char* prefix_copy = NEW_RESOURCE_ARRAY(char, strlen(prefix)+1);
 465       strcpy(prefix_copy, prefix);
 466       prefix_array->at_put_grow(total_count++, prefix_copy);
 467     }
 468   }
 469 
 470   char** all_prefixes = NEW_RESOURCE_ARRAY(char*, total_count);
 471   char** p = all_prefixes;
 472   for (int i = 0; i < total_count; ++i) {
 473     *p++ = prefix_array->at(i);
 474   }
 475   *count_ptr = total_count;
 476   return all_prefixes;
 477 }
 478 
 479 void
 480 JvmtiEnvBase::set_event_callbacks(const jvmtiEventCallbacks* callbacks,
 481                                                jint size_of_callbacks) {
 482   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 483 
 484   size_t byte_cnt = sizeof(jvmtiEventCallbacks);
 485 
 486   // clear in either case to be sure we got any gap between sizes
 487   memset(&_event_callbacks, 0, byte_cnt);
 488 
 489   // Now that JvmtiThreadState_lock is held, prevent a possible race condition where events
 490   // are re-enabled by a call to set event callbacks where the DisposeEnvironment
 491   // occurs after the boiler-plate environment check and before the lock is acquired.
 492   if (callbacks != NULL && is_valid()) {
 493     if (size_of_callbacks < (jint)byte_cnt) {
 494       byte_cnt = size_of_callbacks;
 495     }
 496     memcpy(&_event_callbacks, callbacks, byte_cnt);
 497   }
 498 }
 499 
 500 
 501 // In the fullness of time, all users of the method should instead
 502 // directly use allocate, besides being cleaner and faster, this will
 503 // mean much better out of memory handling
 504 unsigned char *
 505 JvmtiEnvBase::jvmtiMalloc(jlong size) {
 506   unsigned char* mem = NULL;
 507   jvmtiError result = allocate(size, &mem);
 508   assert(result == JVMTI_ERROR_NONE, "Allocate failed");
 509   return mem;
 510 }
 511 
 512 
 513 // Handle management
 514 
 515 jobject JvmtiEnvBase::jni_reference(Handle hndl) {
 516   return JNIHandles::make_local(hndl());
 517 }
 518 
 519 jobject JvmtiEnvBase::jni_reference(JavaThread *thread, Handle hndl) {
 520   return JNIHandles::make_local(thread, hndl());
 521 }
 522 
 523 void JvmtiEnvBase::destroy_jni_reference(jobject jobj) {
 524   JNIHandles::destroy_local(jobj);
 525 }
 526 
 527 void JvmtiEnvBase::destroy_jni_reference(JavaThread *thread, jobject jobj) {
 528   JNIHandles::destroy_local(jobj); // thread is unused.
 529 }
 530 
 531 //
 532 // Threads
 533 //
 534 
 535 jobject *
 536 JvmtiEnvBase::new_jobjectArray(int length, Handle *handles) {
 537   if (length == 0) {
 538     return NULL;
 539   }
 540 
 541   jobject *objArray = (jobject *) jvmtiMalloc(sizeof(jobject) * length);
 542   NULL_CHECK(objArray, NULL);
 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 }
 590 
 591 //
 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.
 978     ObjectMonitor *mon = java_thread->current_waiting_monitor();
 979     if (mon != NULL) {
 980       wait_obj = mon->object();
 981     }
 982   }
 983   oop pending_obj = NULL;
 984   {
 985     // The ObjectMonitor* can't be async deflated since we are either
 986     // at a safepoint or the calling thread is operating on itself so
 987     // it cannot leave the underlying enter() call.
 988     // Save object of current enter() call (if any) for later comparison.
 989     ObjectMonitor *mon = java_thread->current_pending_monitor();
 990     if (mon != NULL) {
 991       pending_obj = mon->object();
 992     }
 993   }
 994 
 995   for (int i = 0; i < mons->length(); i++) {
 996     MonitorInfo *mi = mons->at(i);
 997 
 998     if (mi->owner_is_scalar_replaced()) continue;
 999 
1000     oop obj = mi->owner();
1001     if (obj == NULL) {
1002       // this monitor doesn't have an owning object so skip it
1003       continue;
1004     }
1005 
1006     if (wait_obj == obj) {
1007       // the thread is waiting on this monitor so it isn't really owned
1008       continue;
1009     }
1010 
1011     if (pending_obj == obj) {
1012       // the thread is pending on this monitor so it isn't really owned
1013       continue;
1014     }
1015 
1016     if (owned_monitors_list->length() > 0) {
1017       // Our list has at least one object on it so we have to check
1018       // for recursive object locking
1019       bool found = false;
1020       for (int j = 0; j < owned_monitors_list->length(); j++) {
1021         jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
1022         oop check = JNIHandles::resolve(jobj);
1023         if (check == obj) {
1024           found = true;  // we found the object
1025           break;
1026         }
1027       }
1028 
1029       if (found) {
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);
1333   JavaThread *owning_thread = NULL;
1334   ObjectMonitor *mon = NULL;
1335   jvmtiMonitorUsage ret = {
1336       NULL, 0, 0, NULL, 0, NULL
1337   };
1338 
1339   uint32_t debug_bits = 0;
1340   // first derive the object's owner and entry_count (if any)
1341   {
1342     address owner = NULL;
1343     {
1344       markWord mark = hobj()->mark();
1345 
1346       if (!mark.has_monitor()) {
1347         // this object has a lightweight monitor
1348 
1349         if (mark.has_locker()) {
1350           owner = (address)mark.locker(); // save the address of the Lock word
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;
1392   } else {
1393     // this object has a lightweight monitor
1394     ret.waiter_count = 0;
1395     ret.notify_waiter_count = 0;
1396   }
1397 
1398   // Allocate memory for heavyweight and lightweight monitor.
1399   jvmtiError err;
1400   err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
1401   if (err != JVMTI_ERROR_NONE) {
1402     return err;
1403   }
1404   err = allocate(ret.notify_waiter_count * sizeof(jthread *),
1405                  (unsigned char**)&ret.notify_waiters);
1406   if (err != JVMTI_ERROR_NONE) {
1407     deallocate((unsigned char*)ret.waiters);
1408     return err;
1409   }
1410 
1411   // now derive the rest of the fields
1412   if (mon != NULL) {
1413     // this object has a heavyweight monitor
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;
1642   } else {
1643     *mem_ptr = NULL;
1644     _failed = true;
1645   }
1646   return err;
1647  }
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) {
1734     jint frame_count = sin->info.frame_count;
1735     size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
1736     --si;
1737     memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
1738     if (frames_size == 0) {
1739       si->frame_buffer = NULL;
1740     } else {
1741       memcpy(fi, sin->info.frame_buffer, frames_size);
1742       si->frame_buffer = fi;  // point to the new allocated copy of the frames
1743       fi += frame_count;
1744     }
1745   }
1746   assert(si == _stack_info, "the last copied stack info must be the first record");
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   }
1810   _collector.allocate_and_fill_stacks(_final_thread_count);
1811 }
1812 
1813 // Verifies that the top frame is a java frame in an expected state.
1814 // Deoptimizes frame if needed.
1815 // Checks that the frame method signature matches the return type (tos).
1816 // HandleMark must be defined in the caller only.
1817 // It is to keep a ret_ob_h handle alive after return to the caller.
1818 jvmtiError
1819 JvmtiEnvBase::check_top_frame(Thread* current_thread, JavaThread* java_thread,
1820                               jvalue value, TosState tos, Handle* ret_ob_h) {
1821   ResourceMark rm(current_thread);
1822 
1823   vframe *vf = vframeForNoProcess(java_thread, 0);
1824   NULL_CHECK(vf, JVMTI_ERROR_NO_MORE_FRAMES);
1825 
1826   javaVFrame *jvf = (javaVFrame*) vf;
1827   if (!vf->is_java_frame() || jvf->method()->is_native()) {
1828     return JVMTI_ERROR_OPAQUE_FRAME;
1829   }
1830 
1831   // If the frame is a compiled one, need to deoptimize it.
1832   if (vf->is_compiled_frame()) {
1833     if (!vf->fr().can_be_deoptimized()) {
1834       return JVMTI_ERROR_OPAQUE_FRAME;
1835     }
1836     Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());
1837   }
1838 
1839   // Get information about method return type
1840   Symbol* signature = jvf->method()->signature();
1841 
1842   ResultTypeFinder rtf(signature);
1843   TosState fr_tos = as_TosState(rtf.type());
1844   if (fr_tos != tos) {
1845     if (tos != itos || (fr_tos != btos && fr_tos != ztos && fr_tos != ctos && fr_tos != stos)) {
1846       return JVMTI_ERROR_TYPE_MISMATCH;
1847     }
1848   }
1849 
1850   // Check that the jobject class matches the return type signature.
1851   jobject jobj = value.l;
1852   if (tos == atos && jobj != NULL) { // NULL reference is allowed
1853     Handle ob_h(current_thread, JNIHandles::resolve_external_guard(jobj));
1854     NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
1855     Klass* ob_k = ob_h()->klass();
1856     NULL_CHECK(ob_k, JVMTI_ERROR_INVALID_OBJECT);
1857 
1858     // Method return type signature.
1859     char* ty_sign = 1 + strchr(signature->as_C_string(), JVM_SIGNATURE_ENDFUNC);
1860 
1861     if (!VM_GetOrSetLocal::is_assignable(ty_sign, ob_k, current_thread)) {
1862       return JVMTI_ERROR_TYPE_MISMATCH;
1863     }
1864     *ret_ob_h = ob_h;
1865   }
1866   return JVMTI_ERROR_NONE;
1867 } /* end check_top_frame */
1868 
1869 
1870 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
1871 // Main difference is on the last stage in the interpreter.
1872 // The PopFrame stops method execution to continue execution
1873 // from the same method call instruction.
1874 // The ForceEarlyReturn forces return from method so the execution
1875 // continues at the bytecode following the method call.
1876 
1877 // java_thread - protected by ThreadsListHandle and pre-checked
1878 
1879 jvmtiError
1880 JvmtiEnvBase::force_early_return(JavaThread* java_thread, jvalue value, TosState tos) {
1881   // retrieve or create the state
1882   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1883   if (state == NULL) {
1884     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1885   }
1886 
1887   // Eagerly reallocate scalar replaced objects.
1888   JavaThread* current_thread = JavaThread::current();
1889   EscapeBarrier eb(true, current_thread, java_thread);
1890   if (!eb.deoptimize_objects(0)) {
1891     // Reallocation of scalar replaced objects failed -> return with error
1892     return JVMTI_ERROR_OUT_OF_MEMORY;
1893   }
1894 
1895   SetForceEarlyReturn op(state, value, tos);
1896   if (java_thread == current_thread) {
1897     op.doit(java_thread, true /* self */);
1898   } else {
1899     Handshake::execute(&op, java_thread);
1900   }
1901   return op.result();
1902 }
1903 
1904 void
1905 SetForceEarlyReturn::doit(Thread *target, bool self) {
1906   JavaThread* java_thread = JavaThread::cast(target);
1907   Thread* current_thread = Thread::current();
1908   HandleMark   hm(current_thread);
1909 
1910   if (!self) {
1911     if (!java_thread->is_suspended()) {
1912       _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1913       return;
1914     }
1915   }
1916 
1917   // Check to see if a ForceEarlyReturn was already in progress
1918   if (_state->is_earlyret_pending()) {
1919     // Probably possible for JVMTI clients to trigger this, but the
1920     // JPDA backend shouldn't allow this to happen
1921     _result = JVMTI_ERROR_INTERNAL;
1922     return;
1923   }
1924   {
1925     // The same as for PopFrame. Workaround bug:
1926     //  4812902: popFrame hangs if the method is waiting at a synchronize
1927     // Catch this condition and return an error to avoid hanging.
1928     // Now JVMTI spec allows an implementation to bail out with an opaque
1929     // frame error.
1930     OSThread* osThread = java_thread->osthread();
1931     if (osThread->get_state() == MONITOR_WAIT) {
1932       _result = JVMTI_ERROR_OPAQUE_FRAME;
1933       return;
1934     }
1935   }
1936 
1937   Handle ret_ob_h;
1938   _result = JvmtiEnvBase::check_top_frame(current_thread, java_thread, _value, _tos, &ret_ob_h);
1939   if (_result != JVMTI_ERROR_NONE) {
1940     return;
1941   }
1942   assert(_tos != atos || _value.l == NULL || ret_ob_h() != NULL,
1943          "return object oop must not be NULL if jobject is not NULL");
1944 
1945   // Update the thread state to reflect that the top frame must be
1946   // forced to return.
1947   // The current frame will be returned later when the suspended
1948   // thread is resumed and right before returning from VM to Java.
1949   // (see call_VM_base() in assembler_<cpu>.cpp).
1950 
1951   _state->set_earlyret_pending();
1952   _state->set_earlyret_oop(ret_ob_h());
1953   _state->set_earlyret_value(_value, _tos);
1954 
1955   // Set pending step flag for this early return.
1956   // It is cleared when next step event is posted.
1957   _state->set_pending_step_for_earlyret();
1958 }
1959 
1960 void
1961 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
1962   if ( _error != JVMTI_ERROR_NONE) {
1963     // Error occurred in previous iteration so no need to add
1964     // to the list.
1965     return;
1966   }
1967   // Filter out on stack monitors collected during stack walk.
1968   oop obj = mon->object();
1969   bool found = false;
1970   for (int j = 0; j < _owned_monitors_list->length(); j++) {
1971     jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
1972     oop check = JNIHandles::resolve(jobj);
1973     if (check == obj) {
1974       // On stack monitor already collected during the stack walk.
1975       found = true;
1976       break;
1977     }
1978   }
1979   if (found == false) {
1980     // This is off stack monitor (e.g. acquired via jni MonitorEnter).
1981     jvmtiError err;
1982     jvmtiMonitorStackDepthInfo *jmsdi;
1983     err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1984     if (err != JVMTI_ERROR_NONE) {
1985       _error = err;
1986       return;
1987     }
1988     Handle hobj(Thread::current(), obj);
1989     jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
1990     // stack depth is unknown for this monitor.
1991     jmsdi->stack_depth = -1;
1992     _owned_monitors_list->append(jmsdi);
1993   }
1994 }
1995 
1996 GrowableArray<OopHandle>* JvmtiModuleClosure::_tbl = NULL;
1997 
1998 void JvmtiModuleClosure::do_module(ModuleEntry* entry) {
1999   assert_locked_or_safepoint(Module_lock);
2000   OopHandle module = entry->module_handle();
2001   guarantee(module.resolve() != NULL, "module object is NULL");
2002   _tbl->push(module);
2003 }
2004 
2005 jvmtiError
2006 JvmtiModuleClosure::get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr) {
2007   ResourceMark rm;
2008   MutexLocker mcld(ClassLoaderDataGraph_lock);
2009   MutexLocker ml(Module_lock);
2010 
2011   _tbl = new GrowableArray<OopHandle>(77);
2012   if (_tbl == NULL) {
2013     return JVMTI_ERROR_OUT_OF_MEMORY;
2014   }
2015 
2016   // Iterate over all the modules loaded to the system.
2017   ClassLoaderDataGraph::modules_do(&do_module);
2018 
2019   jint len = _tbl->length();
2020   guarantee(len > 0, "at least one module must be present");
2021 
2022   jobject* array = (jobject*)env->jvmtiMalloc((jlong)(len * sizeof(jobject)));
2023   if (array == NULL) {
2024     return JVMTI_ERROR_OUT_OF_MEMORY;
2025   }
2026   for (jint idx = 0; idx < len; idx++) {
2027     array[idx] = JNIHandles::make_local(Thread::current(), _tbl->at(idx).resolve());
2028   }
2029   _tbl = NULL;
2030   *modules_ptr = array;
2031   *module_count_ptr = len;
2032   return JVMTI_ERROR_NONE;
2033 }
2034 
2035 void
2036 UpdateForPopTopFrameClosure::doit(Thread *target, bool self) {
2037   Thread* current_thread  = Thread::current();
2038   HandleMark hm(current_thread);
2039   JavaThread* java_thread = JavaThread::cast(target);
2040   assert(java_thread == _state->get_thread(), "Must be");
2041 
2042   if (!self && !java_thread->is_suspended()) {
2043     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2044     return;
2045   }
2046 
2047   // Check to see if a PopFrame was already in progress
2048   if (java_thread->popframe_condition() != JavaThread::popframe_inactive) {
2049     // Probably possible for JVMTI clients to trigger this, but the
2050     // JPDA backend shouldn't allow this to happen
2051     _result = JVMTI_ERROR_INTERNAL;
2052     return;
2053   }
2054 
2055   // Was workaround bug
2056   //    4812902: popFrame hangs if the method is waiting at a synchronize
2057   // Catch this condition and return an error to avoid hanging.
2058   // Now JVMTI spec allows an implementation to bail out with an opaque frame error.
2059   OSThread* osThread = java_thread->osthread();
2060   if (osThread->get_state() == MONITOR_WAIT) {
2061     _result = JVMTI_ERROR_OPAQUE_FRAME;
2062     return;
2063   }
2064 
2065   ResourceMark rm(current_thread);
2066   // Check if there is more than one Java frame in this thread, that the top two frames
2067   // are Java (not native) frames, and that there is no intervening VM frame
2068   int frame_count = 0;
2069   bool is_interpreted[2];
2070   intptr_t *frame_sp[2];
2071   // The 2-nd arg of constructor is needed to stop iterating at java entry frame.
2072   for (vframeStream vfs(java_thread, true, false /* process_frames */); !vfs.at_end(); vfs.next()) {
2073     methodHandle mh(current_thread, vfs.method());
2074     if (mh->is_native()) {
2075       _result = JVMTI_ERROR_OPAQUE_FRAME;
2076       return;
2077     }
2078     is_interpreted[frame_count] = vfs.is_interpreted_frame();
2079     frame_sp[frame_count] = vfs.frame_id();
2080     if (++frame_count > 1) break;
2081   }
2082   if (frame_count < 2)  {
2083     // We haven't found two adjacent non-native Java frames on the top.
2084     // There can be two situations here:
2085     //  1. There are no more java frames
2086     //  2. Two top java frames are separated by non-java native frames
2087     if(JvmtiEnvBase::vframeForNoProcess(java_thread, 1) == NULL) {
2088       _result = JVMTI_ERROR_NO_MORE_FRAMES;
2089       return;
2090     } else {
2091       // Intervening non-java native or VM frames separate java frames.
2092       // Current implementation does not support this. See bug #5031735.
2093       // In theory it is possible to pop frames in such cases.
2094       _result = JVMTI_ERROR_OPAQUE_FRAME;
2095       return;
2096     }
2097   }
2098 
2099   // If any of the top 2 frames is a compiled one, need to deoptimize it
2100   for (int i = 0; i < 2; i++) {
2101     if (!is_interpreted[i]) {
2102       Deoptimization::deoptimize_frame(java_thread, frame_sp[i]);
2103     }
2104   }
2105 
2106   // Update the thread state to reflect that the top frame is popped
2107   // so that cur_stack_depth is maintained properly and all frameIDs
2108   // are invalidated.
2109   // The current frame will be popped later when the suspended thread
2110   // is resumed and right before returning from VM to Java.
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 }