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->mounted_vthread() == NULL || jt->mounted_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,
 855                                             jobject *monitor_ptr, bool is_virtual) {
 856   Thread *current_thread = Thread::current();
 857   assert(java_thread->is_handshake_safe_for(current_thread),
 858          "call by myself or at handshake");
 859   if (!is_virtual && JvmtiEnvBase::cthread_with_continuation(java_thread)) {
 860     // Carrier thread with a mounted continuation case.
 861     // No contended monitor can be owned by carrier thread in this case.
 862     *monitor_ptr = nullptr;
 863     return JVMTI_ERROR_NONE;
 864   }
 865   oop obj = NULL;
 866   // The ObjectMonitor* can't be async deflated since we are either
 867   // at a safepoint or the calling thread is operating on itself so
 868   // it cannot leave the underlying wait()/enter() call.
 869   ObjectMonitor *mon = java_thread->current_waiting_monitor();
 870   if (mon == NULL) {
 871     // thread is not doing an Object.wait() call
 872     mon = java_thread->current_pending_monitor();
 873     if (mon != NULL) {
 874       // The thread is trying to enter() an ObjectMonitor.
 875       obj = mon->object();
 876       assert(obj != NULL, "ObjectMonitor should have a valid object!");
 877     }
 878     // implied else: no contended ObjectMonitor
 879   } else {
 880     // thread is doing an Object.wait() call
 881     obj = mon->object();
 882     assert(obj != NULL, "Object.wait() should have an object");
 883   }
 884 
 885   if (obj == NULL) {
 886     *monitor_ptr = NULL;
 887   } else {
 888     HandleMark hm(current_thread);
 889     Handle     hobj(current_thread, obj);
 890     *monitor_ptr = jni_reference(calling_thread, hobj);
 891   }
 892   return JVMTI_ERROR_NONE;
 893 }
 894 
 895 jvmtiError
 896 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
 897                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 898   // Note:
 899   // calling_thread is the thread that requested the list of monitors for java_thread.
 900   // java_thread is the thread owning the monitors.
 901   // current_thread is the thread executing this code, can be a non-JavaThread (e.g. VM Thread).
 902   // And they all may be different threads.
 903   jvmtiError err = JVMTI_ERROR_NONE;
 904   Thread *current_thread = Thread::current();
 905   assert(java_thread->is_handshake_safe_for(current_thread),
 906          "call by myself or at handshake");
 907 
 908   if (JvmtiEnvBase::cthread_with_continuation(java_thread)) {
 909     // Carrier thread with a mounted continuation case.
 910     // No contended monitor can be owned by carrier thread in this case.
 911     return JVMTI_ERROR_NONE;
 912   }
 913   if (java_thread->has_last_Java_frame()) {
 914     ResourceMark rm(current_thread);
 915     HandleMark   hm(current_thread);
 916     RegisterMap  reg_map(java_thread);
 917 
 918     int depth = 0;
 919     for (javaVFrame *jvf = JvmtiEnvBase::get_last_java_vframe(java_thread, &reg_map);
 920          jvf != NULL;
 921          jvf = jvf->java_sender()) {
 922       if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 923         // add locked objects for this frame into list
 924         err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 925         if (err != JVMTI_ERROR_NONE) {
 926           return err;
 927         }
 928       }
 929     }
 930   }
 931 
 932   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 933   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 934   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 935   err = jmc.error();
 936 
 937   return err;
 938 }
 939 
 940 jvmtiError
 941 JvmtiEnvBase::get_owned_monitors(JavaThread* calling_thread, JavaThread* java_thread, javaVFrame* jvf,
 942                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 943   jvmtiError err = JVMTI_ERROR_NONE;
 944 #ifdef ASSERT
 945   uint32_t debug_bits = 0;
 946 #endif
 947   // assert((SafepointSynchronize::is_at_safepoint() ||
 948   //         java_thread->is_thread_fully_suspended(false, &debug_bits)),
 949   //        "at safepoint or target thread is suspended");
 950 
 951   int depth = 0;
 952   for ( ; jvf != NULL; jvf = jvf->java_sender()) {
 953     if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 954       // add locked objects for this frame into list
 955       err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 956       if (err != JVMTI_ERROR_NONE) {
 957         return err;
 958       }
 959     }
 960   }
 961 
 962   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 963   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 964   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 965   err = jmc.error();
 966 
 967   return err;
 968 }
 969 
 970 // Save JNI local handles for any objects that this frame owns.
 971 jvmtiError
 972 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
 973                                  javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, jint stack_depth) {
 974   jvmtiError err = JVMTI_ERROR_NONE;
 975   Thread* current_thread = Thread::current();
 976   ResourceMark rm(current_thread);
 977   HandleMark   hm(current_thread);
 978 
 979   GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 980   if (mons->is_empty()) {
 981     return err;  // this javaVFrame holds no monitors
 982   }
 983 
 984   oop wait_obj = NULL;
 985   {
 986     // The ObjectMonitor* can't be async deflated since we are either
 987     // at a safepoint or the calling thread is operating on itself so
 988     // it cannot leave the underlying wait() call.
 989     // Save object of current wait() call (if any) for later comparison.
 990     ObjectMonitor *mon = java_thread->current_waiting_monitor();
 991     if (mon != NULL) {
 992       wait_obj = mon->object();
 993     }
 994   }
 995   oop pending_obj = NULL;
 996   {
 997     // The ObjectMonitor* can't be async deflated since we are either
 998     // at a safepoint or the calling thread is operating on itself so
 999     // it cannot leave the underlying enter() call.
1000     // Save object of current enter() call (if any) for later comparison.
1001     ObjectMonitor *mon = java_thread->current_pending_monitor();
1002     if (mon != NULL) {
1003       pending_obj = mon->object();
1004     }
1005   }
1006 
1007   for (int i = 0; i < mons->length(); i++) {
1008     MonitorInfo *mi = mons->at(i);
1009 
1010     if (mi->owner_is_scalar_replaced()) continue;
1011 
1012     oop obj = mi->owner();
1013     if (obj == NULL) {
1014       // this monitor doesn't have an owning object so skip it
1015       continue;
1016     }
1017 
1018     if (wait_obj == obj) {
1019       // the thread is waiting on this monitor so it isn't really owned
1020       continue;
1021     }
1022 
1023     if (pending_obj == obj) {
1024       // the thread is pending on this monitor so it isn't really owned
1025       continue;
1026     }
1027 
1028     if (owned_monitors_list->length() > 0) {
1029       // Our list has at least one object on it so we have to check
1030       // for recursive object locking
1031       bool found = false;
1032       for (int j = 0; j < owned_monitors_list->length(); j++) {
1033         jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
1034         oop check = JNIHandles::resolve(jobj);
1035         if (check == obj) {
1036           found = true;  // we found the object
1037           break;
1038         }
1039       }
1040 
1041       if (found) {
1042         // already have this object so don't include it
1043         continue;
1044       }
1045     }
1046 
1047     // add the owning object to our list
1048     jvmtiMonitorStackDepthInfo *jmsdi;
1049     err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1050     if (err != JVMTI_ERROR_NONE) {
1051         return err;
1052     }
1053     Handle hobj(Thread::current(), obj);
1054     jmsdi->monitor = jni_reference(calling_thread, hobj);
1055     jmsdi->stack_depth = stack_depth;
1056     owned_monitors_list->append(jmsdi);
1057   }
1058 
1059   return err;
1060 }
1061 
1062 jvmtiError
1063 JvmtiEnvBase::get_stack_trace(javaVFrame *jvf,
1064                               jint start_depth, jint max_count,
1065                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1066   Thread *current_thread = Thread::current();
1067   ResourceMark rm(current_thread);
1068   HandleMark hm(current_thread);
1069   int count = 0;
1070 
1071   if (start_depth != 0) {
1072     if (start_depth > 0) {
1073       for (int j = 0; j < start_depth && jvf != NULL; j++) {
1074         jvf = jvf->java_sender();
1075       }
1076       if (jvf == NULL) {
1077         // start_depth is deeper than the stack depth
1078         return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1079       }
1080     } else { // start_depth < 0
1081       // we are referencing the starting depth based on the oldest
1082       // part of the stack.
1083       // optimize to limit the number of times that java_sender() is called
1084       javaVFrame *jvf_cursor = jvf;
1085       javaVFrame *jvf_prev = NULL;
1086       javaVFrame *jvf_prev_prev = NULL;
1087       int j = 0;
1088       while (jvf_cursor != NULL) {
1089         jvf_prev_prev = jvf_prev;
1090         jvf_prev = jvf_cursor;
1091         for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
1092           jvf_cursor = jvf_cursor->java_sender();
1093         }
1094       }
1095       if (j == start_depth) {
1096         // previous pointer is exactly where we want to start
1097         jvf = jvf_prev;
1098       } else {
1099         // we need to back up further to get to the right place
1100         if (jvf_prev_prev == NULL) {
1101           // the -start_depth is greater than the stack depth
1102           return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1103         }
1104         // j now is the number of frames on the stack starting with
1105         // jvf_prev, we start from jvf_prev_prev and move older on
1106         // the stack that many, the result is -start_depth frames
1107         // remaining.
1108         jvf = jvf_prev_prev;
1109         for (; j < 0; j++) {
1110           jvf = jvf->java_sender();
1111         }
1112       }
1113     }
1114   }
1115   for (; count < max_count && jvf != NULL; count++) {
1116     frame_buffer[count].method = jvf->method()->jmethod_id();
1117     frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
1118     jvf = jvf->java_sender();
1119   }
1120   *count_ptr = count;
1121   return JVMTI_ERROR_NONE;
1122 }
1123 
1124 jvmtiError
1125 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
1126                               jint start_depth, jint max_count,
1127                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1128 #ifdef ASSERT
1129   uint32_t debug_bits = 0;
1130 #endif
1131   Thread *current_thread = Thread::current();
1132   assert(SafepointSynchronize::is_at_safepoint() ||
1133          java_thread->is_handshake_safe_for(current_thread),
1134          "call by myself / at safepoint / at handshake");
1135   int count = 0;
1136   jvmtiError err = JVMTI_ERROR_NONE;
1137 
1138   if (java_thread->has_last_Java_frame()) {
1139     RegisterMap reg_map(java_thread, true, true);
1140     ResourceMark rm(current_thread);
1141     javaVFrame *jvf = get_last_java_vframe(java_thread, &reg_map);
1142 
1143     err = get_stack_trace(jvf, start_depth, max_count, frame_buffer, count_ptr);
1144   } else {
1145     *count_ptr = 0;
1146     if (start_depth != 0) {
1147       // no frames and there is a starting depth
1148       err = JVMTI_ERROR_ILLEGAL_ARGUMENT;
1149     }
1150   }
1151   return err;
1152 }
1153 
1154 jint
1155 JvmtiEnvBase::get_frame_count(javaVFrame *jvf) {
1156   int count = 0;
1157 
1158   while (jvf != NULL) {
1159     Method* method = jvf->method();
1160     jvf = jvf->java_sender();
1161     count++;
1162   }
1163   return count;
1164 }
1165 
1166 jvmtiError
1167 JvmtiEnvBase::get_frame_count(JavaThread* jt, jint *count_ptr) {
1168   Thread *current_thread = Thread::current();
1169   assert(current_thread == jt ||
1170          SafepointSynchronize::is_at_safepoint() ||
1171          jt->is_handshake_safe_for(current_thread),
1172          "call by myself / at safepoint / at handshake");
1173 
1174   if (!jt->has_last_Java_frame()) { // no Java frames
1175     *count_ptr = 0;
1176   } else {
1177     ResourceMark rm(current_thread);
1178     RegisterMap reg_map(jt, true, true);
1179     javaVFrame *jvf = get_last_java_vframe(jt, &reg_map);
1180 
1181     *count_ptr = get_frame_count(jvf);
1182   }
1183   return JVMTI_ERROR_NONE;
1184 }
1185 
1186 jvmtiError
1187 JvmtiEnvBase::get_frame_count(oop vthread_oop, jint *count_ptr) {
1188   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1189     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1190   }
1191   Thread *current_thread = Thread::current();
1192   ResourceMark rm(current_thread);
1193   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1194 
1195   *count_ptr = get_frame_count(jvf);
1196   return JVMTI_ERROR_NONE;
1197 }
1198 
1199 jvmtiError
1200 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
1201                                  jmethodID* method_ptr, jlocation* location_ptr) {
1202   Thread* current_thread = Thread::current();
1203   assert(java_thread->is_handshake_safe_for(current_thread),
1204          "call by myself or at handshake");
1205   ResourceMark rm(current_thread);
1206 
1207   vframe *vf = vframeForNoProcess(java_thread, depth, true /* for cont */);
1208   if (vf == NULL) {
1209     return JVMTI_ERROR_NO_MORE_FRAMES;
1210   }
1211 
1212   // vframeFor should return a java frame. If it doesn't
1213   // it means we've got an internal error and we return the
1214   // error in product mode. In debug mode we will instead
1215   // attempt to cast the vframe to a javaVFrame and will
1216   // cause an assertion/crash to allow further diagnosis.
1217 #ifdef PRODUCT
1218   if (!vf->is_java_frame()) {
1219     return JVMTI_ERROR_INTERNAL;
1220   }
1221 #endif
1222 
1223   HandleMark hm(current_thread);
1224   javaVFrame *jvf = javaVFrame::cast(vf);
1225   Method* method = jvf->method();
1226   if (method->is_native()) {
1227     *location_ptr = -1;
1228   } else {
1229     *location_ptr = jvf->bci();
1230   }
1231   *method_ptr = method->jmethod_id();
1232 
1233   return JVMTI_ERROR_NONE;
1234 }
1235 
1236 jvmtiError
1237 JvmtiEnvBase::get_frame_location(oop vthread_oop, jint depth,
1238                                  jmethodID* method_ptr, jlocation* location_ptr) {
1239   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1240     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1241   }
1242   Thread* cur_thread = Thread::current();
1243   ResourceMark rm(cur_thread);
1244   HandleMark hm(cur_thread);
1245   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1246   int cur_depth = 0;
1247 
1248   while (jvf != NULL && cur_depth < depth) {
1249     Method* method = jvf->method();
1250     jvf = jvf->java_sender();
1251     cur_depth++;
1252   }
1253   assert(depth >= cur_depth, "ran out of frames too soon");
1254   if (jvf == NULL) {
1255     return JVMTI_ERROR_NO_MORE_FRAMES;
1256   }
1257   Method* method = jvf->method();
1258   if (method->is_native()) {
1259     *location_ptr = -1;
1260   } else {
1261     *location_ptr = jvf->bci();
1262   }
1263   *method_ptr = method->jmethod_id();
1264 
1265   return JVMTI_ERROR_NONE;
1266 }
1267 
1268 bool
1269 JvmtiEnvBase::cthread_with_mounted_vthread(JavaThread* jt) {
1270   oop thread_oop = jt->threadObj();
1271   assert(thread_oop != NULL, "sanity check");
1272   oop mounted_vt = jt->mounted_vthread();
1273 
1274   return (mounted_vt != NULL && mounted_vt != thread_oop);
1275 }
1276 
1277 bool
1278 JvmtiEnvBase::cthread_with_continuation(JavaThread* jt) {
1279   ContinuationEntry* cont = NULL;
1280   if (jt->has_last_Java_frame()) {
1281     cont = jt->last_continuation(java_lang_VirtualThread::vthread_scope());
1282   }
1283   return (cont != NULL && cthread_with_mounted_vthread(jt));
1284 }
1285 
1286 jvmtiError
1287 JvmtiEnvBase::get_threadOop_and_JavaThread(ThreadsList* t_list, jthread thread,
1288                                            JavaThread** jt_pp, oop* thread_oop_p) {
1289   JavaThread* cur_thread = JavaThread::current();
1290   JavaThread* java_thread = NULL;
1291   oop thread_oop = NULL;
1292 
1293   if (thread == NULL) {
1294     java_thread = cur_thread;
1295     thread_oop = get_vthread_or_thread_oop(java_thread);
1296     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::Thread_klass())) {
1297       return JVMTI_ERROR_INVALID_THREAD;
1298     }
1299   } else {
1300     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(t_list, thread, &java_thread, &thread_oop);
1301     if (err != JVMTI_ERROR_NONE) {
1302       // We got an error code so we don't have a JavaThread*, but only return
1303       // an error from here if we didn't get a valid thread_oop. In a vthread case
1304       // the cv_external_thread_to_JavaThread is expected to correctly set the
1305       // thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1306       if (thread_oop == NULL || err != JVMTI_ERROR_INVALID_THREAD) {
1307         return err;
1308       }
1309     }
1310     if (java_thread == NULL && java_lang_VirtualThread::is_instance(thread_oop)) {
1311       oop cont = java_lang_VirtualThread::continuation(thread_oop);
1312       if (jdk_internal_vm_Continuation::is_mounted(cont)) {
1313         oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_oop);
1314         // Returned carrier_thread can be NULL for a mounted continuation.
1315         if (carrier_thread != NULL) {
1316           java_thread = java_lang_Thread::thread(carrier_thread);
1317         }
1318       }
1319     }
1320   }
1321   *jt_pp = java_thread;
1322   *thread_oop_p = thread_oop;
1323   return JVMTI_ERROR_NONE;
1324 }
1325 
1326 jvmtiError
1327 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
1328   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1329   Thread* current_thread = VMThread::vm_thread();
1330   assert(current_thread == Thread::current(), "must be");
1331 
1332   HandleMark hm(current_thread);
1333   Handle hobj;
1334 
1335   // Check arguments
1336   {
1337     oop mirror = JNIHandles::resolve_external_guard(object);
1338     NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
1339     NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
1340 
1341     hobj = Handle(current_thread, mirror);
1342   }
1343 
1344   ThreadsListHandle tlh(current_thread);
1345   JavaThread *owning_thread = NULL;
1346   ObjectMonitor *mon = NULL;
1347   jvmtiMonitorUsage ret = {
1348       NULL, 0, 0, NULL, 0, NULL
1349   };
1350 
1351   uint32_t debug_bits = 0;
1352   // first derive the object's owner and entry_count (if any)
1353   {
1354     address owner = NULL;
1355     {
1356       markWord mark = hobj()->mark();
1357 
1358       if (!mark.has_monitor()) {
1359         // this object has a lightweight monitor
1360 
1361         if (mark.has_locker()) {
1362           owner = (address)mark.locker(); // save the address of the Lock word
1363         }
1364         // implied else: no owner
1365       } else {
1366         // this object has a heavyweight monitor
1367         mon = mark.monitor();
1368 
1369         // The owner field of a heavyweight monitor may be NULL for no
1370         // owner, a JavaThread * or it may still be the address of the
1371         // Lock word in a JavaThread's stack. A monitor can be inflated
1372         // by a non-owning JavaThread, but only the owning JavaThread
1373         // can change the owner field from the Lock word to the
1374         // JavaThread * and it may not have done that yet.
1375         owner = (address)mon->owner();
1376       }
1377     }
1378 
1379     if (owner != NULL) {
1380       // This monitor is owned so we have to find the owning JavaThread.
1381       owning_thread = Threads::owning_thread_from_monitor_owner(tlh.list(), owner);
1382       assert(owning_thread != NULL, "owning JavaThread must not be NULL");
1383       Handle     th(current_thread, get_vthread_or_thread_oop(owning_thread));
1384       ret.owner = (jthread)jni_reference(calling_thread, th);
1385     }
1386 
1387     if (owning_thread != NULL) {  // monitor is owned
1388       // The recursions field of a monitor does not reflect recursions
1389       // as lightweight locks before inflating the monitor are not included.
1390       // We have to count the number of recursive monitor entries the hard way.
1391       // We pass a handle to survive any GCs along the way.
1392       ret.entry_count = count_locked_objects(owning_thread, hobj);
1393     }
1394     // implied else: entry_count == 0
1395   }
1396 
1397   jint nWant = 0, nWait = 0;
1398   if (mon != NULL) {
1399     // this object has a heavyweight monitor
1400     nWant = mon->contentions(); // # of threads contending for monitor
1401     nWait = mon->waiters();     // # of threads in Object.wait()
1402     ret.waiter_count = nWant + nWait;
1403     ret.notify_waiter_count = nWait;
1404   } else {
1405     // this object has a lightweight monitor
1406     ret.waiter_count = 0;
1407     ret.notify_waiter_count = 0;
1408   }
1409 
1410   // Allocate memory for heavyweight and lightweight monitor.
1411   jvmtiError err;
1412   err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
1413   if (err != JVMTI_ERROR_NONE) {
1414     return err;
1415   }
1416   err = allocate(ret.notify_waiter_count * sizeof(jthread *),
1417                  (unsigned char**)&ret.notify_waiters);
1418   if (err != JVMTI_ERROR_NONE) {
1419     deallocate((unsigned char*)ret.waiters);
1420     return err;
1421   }
1422 
1423   // now derive the rest of the fields
1424   if (mon != NULL) {
1425     // this object has a heavyweight monitor
1426 
1427     // Number of waiters may actually be less than the waiter count.
1428     // So NULL out memory so that unused memory will be NULL.
1429     memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1430     memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1431 
1432     if (ret.waiter_count > 0) {
1433       // we have contending and/or waiting threads
1434       if (nWant > 0) {
1435         // we have contending threads
1436         ResourceMark rm(current_thread);
1437         // get_pending_threads returns only java thread so we do not need to
1438         // check for non java threads.
1439         GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(tlh.list(), nWant, (address)mon);
1440         if (wantList->length() < nWant) {
1441           // robustness: the pending list has gotten smaller
1442           nWant = wantList->length();
1443         }
1444         for (int i = 0; i < nWant; i++) {
1445           JavaThread *pending_thread = wantList->at(i);
1446           Handle th(current_thread, get_vthread_or_thread_oop(pending_thread));
1447           ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1448         }
1449       }
1450       if (nWait > 0) {
1451         // we have threads in Object.wait()
1452         int offset = nWant;  // add after any contending threads
1453         ObjectWaiter *waiter = mon->first_waiter();
1454         for (int i = 0, j = 0; i < nWait; i++) {
1455           if (waiter == NULL) {
1456             // robustness: the waiting list has gotten smaller
1457             nWait = j;
1458             break;
1459           }
1460           JavaThread *w = mon->thread_of_waiter(waiter);
1461           if (w != NULL) {
1462             // If the thread was found on the ObjectWaiter list, then
1463             // it has not been notified. This thread can't change the
1464             // state of the monitor so it doesn't need to be suspended.
1465             Handle th(current_thread, get_vthread_or_thread_oop(w));
1466             ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1467             ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1468           }
1469           waiter = mon->next_waiter(waiter);
1470         }
1471       }
1472     } // ThreadsListHandle is destroyed here.
1473 
1474     // Adjust count. nWant and nWait count values may be less than original.
1475     ret.waiter_count = nWant + nWait;
1476     ret.notify_waiter_count = nWait;
1477   } else {
1478     // this object has a lightweight monitor and we have nothing more
1479     // to do here because the defaults are just fine.
1480   }
1481 
1482   // we don't update return parameter unless everything worked
1483   *info_ptr = ret;
1484 
1485   return JVMTI_ERROR_NONE;
1486 }
1487 
1488 jvmtiError
1489 JvmtiEnvBase::check_thread_list(jint count, const jthread* list) {
1490   if (list == NULL && count != 0) {
1491     return JVMTI_ERROR_NULL_POINTER;
1492   }
1493   for (int i = 0; i < count; i++) {
1494     jthread thread = list[i];
1495     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1496     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::VirtualThread_klass())) {
1497       return JVMTI_ERROR_INVALID_THREAD;
1498     }
1499   }
1500   return JVMTI_ERROR_NONE;
1501 }
1502 
1503 bool
1504 JvmtiEnvBase::is_in_thread_list(jint count, const jthread* list, oop jt_oop) {
1505   for (int idx = 0; idx < count; idx++) {
1506     jthread thread = list[idx];
1507     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1508     if (thread_oop == jt_oop) {
1509       return true;
1510     }
1511   }
1512   return false;
1513 }
1514 
1515 jvmtiError
1516 JvmtiEnvBase::suspend_thread(oop thread_oop, JavaThread* java_thread, bool single_suspend,
1517                              int* need_safepoint_p) {
1518   JavaThread* current = JavaThread::current();
1519   HandleMark hm(current);
1520   Handle thread_h(current, thread_oop);
1521   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1522 
1523   if (is_virtual) {
1524     if (single_suspend) {
1525       if (JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1526         return JVMTI_ERROR_THREAD_SUSPENDED;
1527       }
1528       JvmtiVTSuspender::register_vthread_suspend(thread_h());
1529       // Check if virtual thread is mounted and there is a java_thread.
1530       // A non-NULL java_thread is always passed in the !single_suspend case.
1531       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1532       java_thread = carrier_thread == NULL ? NULL : java_lang_Thread::thread(carrier_thread);
1533     }
1534     // The java_thread can be still blocked in VTMT transition after a previous JVMTI resume call.
1535     // There is no need to suspend the java_thread in this case. After vthread unblocking,
1536     // it will check for ext_suspend request and suspend itself if necessary.
1537     if (java_thread == NULL || java_thread->is_suspended()) {
1538       // We are done if the virtual thread is unmounted or
1539       // the java_thread is externally suspended.
1540       return JVMTI_ERROR_NONE;
1541     }
1542     // The virtual thread is mounted: suspend the java_thread.
1543   }
1544   // Don't allow hidden thread suspend request.
1545   if (java_thread->is_hidden_from_external_view()) {
1546     return JVMTI_ERROR_NONE;
1547   }
1548   bool is_passive_cthread = is_passive_carrier_thread(java_thread, thread_h());
1549 
1550   // A case of non-virtual thread.
1551   if (!is_virtual) {
1552     // Thread.suspend() is used in some tests. It sets jt->is_suspended() only.
1553     if (java_thread->is_thread_suspended() ||
1554         (!is_passive_cthread && java_thread->is_suspended())) {
1555       return JVMTI_ERROR_THREAD_SUSPENDED;
1556     }
1557     java_thread->set_thread_suspended();
1558   }
1559   assert(JvmtiVTMTDisabler::VTMT_count() == 0, "must be 0");
1560   assert(!java_thread->is_in_VTMT(), "sanity check");
1561 
1562   assert(!single_suspend || (!is_virtual && java_thread->is_thread_suspended()) ||
1563           (is_virtual && JvmtiVTSuspender::is_vthread_suspended(thread_h())),
1564          "sanity check");
1565 
1566   // An attempt to handshake-suspend a passive carrier thread will result in
1567   // suspension of mounted virtual thread. So, we just mark it as suspended
1568   // and it will be actually suspended at virtual thread unmount transition.
1569   if (!is_passive_cthread) {
1570     assert(single_suspend || is_virtual, "SuspendAllVirtualThreads should never suspend non-virtual threads");
1571     // Case of mounted virtual or attached carrier thread.
1572     if (!JvmtiSuspendControl::suspend(java_thread)) {
1573       // Thread is already suspended or in process of exiting.
1574       if (java_thread->is_exiting()) {
1575         // The thread was in the process of exiting.
1576         return JVMTI_ERROR_THREAD_NOT_ALIVE;
1577       }
1578     }
1579   }
1580   return JVMTI_ERROR_NONE;
1581 }
1582 
1583 jvmtiError
1584 JvmtiEnvBase::resume_thread(oop thread_oop, JavaThread* java_thread, bool single_suspend) {
1585   JavaThread* current = JavaThread::current();
1586   HandleMark hm(current);
1587   Handle thread_h(current, thread_oop);
1588   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1589 
1590   if (is_virtual) {
1591     if (single_suspend) {
1592       if (!JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1593         return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1594       }
1595       JvmtiVTSuspender::register_vthread_resume(thread_h());
1596       // Check if virtual thread is mounted and there is a java_thread.
1597       // A non-NULL java_thread is always passed in the !single_suspend case.
1598       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1599       java_thread = carrier_thread == NULL ? NULL : java_lang_Thread::thread(carrier_thread);
1600     }
1601     // The java_thread can be still blocked in VTMT transition after a previous JVMTI suspend call.
1602     // There is no need to resume the java_thread in this case. After vthread unblocking,
1603     // it will check for is_vthread_suspended request and remain resumed if necessary.
1604     if (java_thread == NULL || !java_thread->is_suspended()) {
1605       // We are done if the virtual thread is unmounted or
1606       // the java_thread is not externally suspended.
1607       return JVMTI_ERROR_NONE;
1608     }
1609     // The virtual thread is mounted and java_thread is supended: resume the java_thread.
1610   }
1611   // Don't allow hidden thread resume request.
1612   if (java_thread->is_hidden_from_external_view()) {
1613     return JVMTI_ERROR_NONE;
1614   }
1615   // A case of a non-virtual thread.
1616   if (!is_virtual) {
1617     if (!java_thread->is_thread_suspended() &&
1618         (thread_h() == java_thread->vthread() && !java_thread->is_suspended())) {
1619       return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1620     }
1621     java_thread->clear_thread_suspended();
1622   }
1623   assert(!java_thread->is_in_VTMT(), "sanity check");
1624   if (is_virtual || thread_h() == java_thread->vthread()) {
1625     assert(single_suspend || is_virtual, "ResumeAllVirtualThreads should never resume non-virtual threads");
1626     if (java_thread->is_suspended()) {
1627       if (!JvmtiSuspendControl::resume(java_thread)) {
1628         return JVMTI_ERROR_INTERNAL;
1629       }
1630     }
1631   }
1632   return JVMTI_ERROR_NONE;
1633 }
1634 
1635 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1636   _env = env;
1637   _allocations = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<unsigned char*>(20, mtServiceability);
1638   _failed = false;
1639 }
1640 ResourceTracker::~ResourceTracker() {
1641   if (_failed) {
1642     for (int i=0; i<_allocations->length(); i++) {
1643       _env->deallocate(_allocations->at(i));
1644     }
1645   }
1646   delete _allocations;
1647 }
1648 
1649 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1650   unsigned char *ptr;
1651   jvmtiError err = _env->allocate(size, &ptr);
1652   if (err == JVMTI_ERROR_NONE) {
1653     _allocations->append(ptr);
1654     *mem_ptr = ptr;
1655   } else {
1656     *mem_ptr = NULL;
1657     _failed = true;
1658   }
1659   return err;
1660  }
1661 
1662 unsigned char* ResourceTracker::allocate(jlong size) {
1663   unsigned char* ptr;
1664   allocate(size, &ptr);
1665   return ptr;
1666 }
1667 
1668 char* ResourceTracker::strdup(const char* str) {
1669   char *dup_str = (char*)allocate(strlen(str)+1);
1670   if (dup_str != NULL) {
1671     strcpy(dup_str, str);
1672   }
1673   return dup_str;
1674 }
1675 
1676 struct StackInfoNode {
1677   struct StackInfoNode *next;
1678   jvmtiStackInfo info;
1679 };
1680 
1681 
1682 // Create a jvmtiStackInfo inside a linked list node and create a
1683 // buffer for the frame information, both allocated as resource objects.
1684 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1685 // Note that either or both of thr and thread_oop
1686 // may be null if the thread is new or has exited.
1687 void
1688 MultipleStackTracesCollector::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1689 #ifdef ASSERT
1690   Thread *current_thread = Thread::current();
1691   assert(SafepointSynchronize::is_at_safepoint() ||
1692          thr == NULL ||
1693          thr->is_handshake_safe_for(current_thread),
1694          "unmounted virtual thread / call by myself / at safepoint / at handshake");
1695 #endif
1696 
1697   jint state = 0;
1698   struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
1699   jvmtiStackInfo *infop = &(node->info);
1700 
1701   node->next = head();
1702   set_head(node);
1703   infop->frame_count = 0;
1704   infop->frame_buffer = NULL;
1705   infop->thread = jt;
1706 
1707   // Support for virtual threads
1708   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1709     state = JvmtiEnvBase::get_vthread_state(thread_oop);
1710 
1711     if ((state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1712       javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(thread_oop);
1713       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1714       _result = env()->get_stack_trace(jvf, 0, max_frame_count(),
1715                                      infop->frame_buffer, &(infop->frame_count));
1716     }
1717   } else {
1718     state = JvmtiEnvBase::get_thread_state(thread_oop, thr);
1719     if (thr != NULL && (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1720       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1721       _result = env()->get_stack_trace(thr, 0, max_frame_count(),
1722                                        infop->frame_buffer, &(infop->frame_count));
1723     }
1724   }
1725   _frame_count_total += infop->frame_count;
1726   infop->state = state;
1727 }
1728 
1729 // Based on the stack information in the linked list, allocate memory
1730 // block to return and fill it from the info in the linked list.
1731 void
1732 MultipleStackTracesCollector::allocate_and_fill_stacks(jint thread_count) {
1733   // do I need to worry about alignment issues?
1734   jlong alloc_size =  thread_count       * sizeof(jvmtiStackInfo)
1735                     + _frame_count_total * sizeof(jvmtiFrameInfo);
1736   env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1737 
1738   // pointers to move through the newly allocated space as it is filled in
1739   jvmtiStackInfo *si = _stack_info + thread_count;      // bottom of stack info
1740   jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si;            // is the top of frame info
1741 
1742   // copy information in resource area into allocated buffer
1743   // insert stack info backwards since linked list is backwards
1744   // insert frame info forwards
1745   // walk the StackInfoNodes
1746   for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {
1747     jint frame_count = sin->info.frame_count;
1748     size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
1749     --si;
1750     memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
1751     if (frames_size == 0) {
1752       si->frame_buffer = NULL;
1753     } else {
1754       memcpy(fi, sin->info.frame_buffer, frames_size);
1755       si->frame_buffer = fi;  // point to the new allocated copy of the frames
1756       fi += frame_count;
1757     }
1758   }
1759   assert(si == _stack_info, "the last copied stack info must be the first record");
1760   assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1761          "the last copied frame info must be the last record");
1762 }
1763 
1764 
1765 void
1766 VM_GetThreadListStackTraces::doit() {
1767   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1768 
1769   ResourceMark rm;
1770   ThreadsListHandle tlh;
1771   for (int i = 0; i < _thread_count; ++i) {
1772     jthread jt = _thread_list[i];
1773     JavaThread* java_thread = NULL;
1774     oop thread_oop = NULL;
1775     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), jt, &java_thread, &thread_oop);
1776     if (err != JVMTI_ERROR_NONE) {
1777       // We got an error code so we don't have a JavaThread *, but
1778       // only return an error from here if we didn't get a valid
1779       // thread_oop.
1780       // In the virtual thread case the cv_external_thread_to_JavaThread is expected to correctly set
1781       // the thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1782       if (thread_oop == NULL) {
1783         _collector.set_result(err);
1784         return;
1785       }
1786       // We have a valid thread_oop.
1787     }
1788     _collector.fill_frames(jt, java_thread, thread_oop);
1789   }
1790   _collector.allocate_and_fill_stacks(_thread_count);
1791 }
1792 
1793 void
1794 GetSingleStackTraceClosure::do_thread(Thread *target) {
1795     JavaThread *jt = JavaThread::cast(target);
1796     oop thread_oop = jt->threadObj();
1797 
1798     if (!jt->is_exiting() && thread_oop != NULL) {
1799         ResourceMark rm;
1800         _collector.fill_frames(_jthread, jt, thread_oop);
1801         _collector.allocate_and_fill_stacks(1);
1802     }
1803 }
1804 
1805 void
1806 VM_GetAllStackTraces::doit() {
1807   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1808 
1809   ResourceMark rm;
1810   _final_thread_count = 0;
1811   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1812     oop thread_oop = jt->threadObj();
1813     if (thread_oop != NULL &&
1814         !jt->is_exiting() &&
1815         java_lang_Thread::is_alive(thread_oop) &&
1816         !jt->is_hidden_from_external_view()) {
1817       ++_final_thread_count;
1818       // Handle block of the calling thread is used to create local refs.
1819       _collector.fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
1820                              jt, thread_oop);
1821     }
1822   }
1823   _collector.allocate_and_fill_stacks(_final_thread_count);
1824 }
1825 
1826 // Verifies that the top frame is a java frame in an expected state.
1827 // Deoptimizes frame if needed.
1828 // Checks that the frame method signature matches the return type (tos).
1829 // HandleMark must be defined in the caller only.
1830 // It is to keep a ret_ob_h handle alive after return to the caller.
1831 jvmtiError
1832 JvmtiEnvBase::check_top_frame(Thread* current_thread, JavaThread* java_thread,
1833                               jvalue value, TosState tos, Handle* ret_ob_h) {
1834   ResourceMark rm(current_thread);
1835 
1836   vframe *vf = vframeForNoProcess(java_thread, 0);
1837   NULL_CHECK(vf, JVMTI_ERROR_NO_MORE_FRAMES);
1838 
1839   javaVFrame *jvf = (javaVFrame*) vf;
1840   if (!vf->is_java_frame() || jvf->method()->is_native()) {
1841     return JVMTI_ERROR_OPAQUE_FRAME;
1842   }
1843 
1844   // If the frame is a compiled one, need to deoptimize it.
1845   if (vf->is_compiled_frame()) {
1846     if (!vf->fr().can_be_deoptimized()) {
1847       return JVMTI_ERROR_OPAQUE_FRAME;
1848     }
1849     Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());
1850   }
1851 
1852   // Get information about method return type
1853   Symbol* signature = jvf->method()->signature();
1854 
1855   ResultTypeFinder rtf(signature);
1856   TosState fr_tos = as_TosState(rtf.type());
1857   if (fr_tos != tos) {
1858     if (tos != itos || (fr_tos != btos && fr_tos != ztos && fr_tos != ctos && fr_tos != stos)) {
1859       return JVMTI_ERROR_TYPE_MISMATCH;
1860     }
1861   }
1862 
1863   // Check that the jobject class matches the return type signature.
1864   jobject jobj = value.l;
1865   if (tos == atos && jobj != NULL) { // NULL reference is allowed
1866     Handle ob_h(current_thread, JNIHandles::resolve_external_guard(jobj));
1867     NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
1868     Klass* ob_k = ob_h()->klass();
1869     NULL_CHECK(ob_k, JVMTI_ERROR_INVALID_OBJECT);
1870 
1871     // Method return type signature.
1872     char* ty_sign = 1 + strchr(signature->as_C_string(), JVM_SIGNATURE_ENDFUNC);
1873 
1874     if (!VM_GetOrSetLocal::is_assignable(ty_sign, ob_k, current_thread)) {
1875       return JVMTI_ERROR_TYPE_MISMATCH;
1876     }
1877     *ret_ob_h = ob_h;
1878   }
1879   return JVMTI_ERROR_NONE;
1880 } /* end check_top_frame */
1881 
1882 
1883 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
1884 // Main difference is on the last stage in the interpreter.
1885 // The PopFrame stops method execution to continue execution
1886 // from the same method call instruction.
1887 // The ForceEarlyReturn forces return from method so the execution
1888 // continues at the bytecode following the method call.
1889 
1890 // java_thread - protected by ThreadsListHandle and pre-checked
1891 
1892 jvmtiError
1893 JvmtiEnvBase::force_early_return(JavaThread* java_thread, jvalue value, TosState tos) {
1894   // retrieve or create the state
1895   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1896   if (state == NULL) {
1897     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1898   }
1899 
1900   // Eagerly reallocate scalar replaced objects.
1901   JavaThread* current_thread = JavaThread::current();
1902   EscapeBarrier eb(true, current_thread, java_thread);
1903   if (!eb.deoptimize_objects(0)) {
1904     // Reallocation of scalar replaced objects failed -> return with error
1905     return JVMTI_ERROR_OUT_OF_MEMORY;
1906   }
1907 
1908   SetForceEarlyReturn op(state, value, tos);
1909   if (java_thread == current_thread) {
1910     op.doit(java_thread, true /* self */);
1911   } else {
1912     Handshake::execute(&op, java_thread);
1913   }
1914   return op.result();
1915 }
1916 
1917 void
1918 SetForceEarlyReturn::doit(Thread *target, bool self) {
1919   JavaThread* java_thread = JavaThread::cast(target);
1920   Thread* current_thread = Thread::current();
1921   HandleMark   hm(current_thread);
1922 
1923   if (java_thread->is_exiting()) {
1924     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
1925   }
1926   if (!self) {
1927     if (!java_thread->is_suspended()) {
1928       _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1929       return;
1930     }
1931   }
1932 
1933   // Check to see if a ForceEarlyReturn was already in progress
1934   if (_state->is_earlyret_pending()) {
1935     // Probably possible for JVMTI clients to trigger this, but the
1936     // JPDA backend shouldn't allow this to happen
1937     _result = JVMTI_ERROR_INTERNAL;
1938     return;
1939   }
1940   {
1941     // The same as for PopFrame. Workaround bug:
1942     //  4812902: popFrame hangs if the method is waiting at a synchronize
1943     // Catch this condition and return an error to avoid hanging.
1944     // Now JVMTI spec allows an implementation to bail out with an opaque
1945     // frame error.
1946     OSThread* osThread = java_thread->osthread();
1947     if (osThread->get_state() == MONITOR_WAIT) {
1948       _result = JVMTI_ERROR_OPAQUE_FRAME;
1949       return;
1950     }
1951   }
1952 
1953   Handle ret_ob_h;
1954   _result = JvmtiEnvBase::check_top_frame(current_thread, java_thread, _value, _tos, &ret_ob_h);
1955   if (_result != JVMTI_ERROR_NONE) {
1956     return;
1957   }
1958   assert(_tos != atos || _value.l == NULL || ret_ob_h() != NULL,
1959          "return object oop must not be NULL if jobject is not NULL");
1960 
1961   // Update the thread state to reflect that the top frame must be
1962   // forced to return.
1963   // The current frame will be returned later when the suspended
1964   // thread is resumed and right before returning from VM to Java.
1965   // (see call_VM_base() in assembler_<cpu>.cpp).
1966 
1967   _state->set_earlyret_pending();
1968   _state->set_earlyret_oop(ret_ob_h());
1969   _state->set_earlyret_value(_value, _tos);
1970 
1971   // Set pending step flag for this early return.
1972   // It is cleared when next step event is posted.
1973   _state->set_pending_step_for_earlyret();
1974 }
1975 
1976 void
1977 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
1978   if ( _error != JVMTI_ERROR_NONE) {
1979     // Error occurred in previous iteration so no need to add
1980     // to the list.
1981     return;
1982   }
1983   // Filter out on stack monitors collected during stack walk.
1984   oop obj = mon->object();
1985   bool found = false;
1986   for (int j = 0; j < _owned_monitors_list->length(); j++) {
1987     jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
1988     oop check = JNIHandles::resolve(jobj);
1989     if (check == obj) {
1990       // On stack monitor already collected during the stack walk.
1991       found = true;
1992       break;
1993     }
1994   }
1995   if (found == false) {
1996     // This is off stack monitor (e.g. acquired via jni MonitorEnter).
1997     jvmtiError err;
1998     jvmtiMonitorStackDepthInfo *jmsdi;
1999     err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
2000     if (err != JVMTI_ERROR_NONE) {
2001       _error = err;
2002       return;
2003     }
2004     Handle hobj(Thread::current(), obj);
2005     jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
2006     // stack depth is unknown for this monitor.
2007     jmsdi->stack_depth = -1;
2008     _owned_monitors_list->append(jmsdi);
2009   }
2010 }
2011 
2012 GrowableArray<OopHandle>* JvmtiModuleClosure::_tbl = NULL;
2013 
2014 void JvmtiModuleClosure::do_module(ModuleEntry* entry) {
2015   assert_locked_or_safepoint(Module_lock);
2016   OopHandle module = entry->module_handle();
2017   guarantee(module.resolve() != NULL, "module object is NULL");
2018   _tbl->push(module);
2019 }
2020 
2021 jvmtiError
2022 JvmtiModuleClosure::get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr) {
2023   ResourceMark rm;
2024   MutexLocker mcld(ClassLoaderDataGraph_lock);
2025   MutexLocker ml(Module_lock);
2026 
2027   _tbl = new GrowableArray<OopHandle>(77);
2028   if (_tbl == NULL) {
2029     return JVMTI_ERROR_OUT_OF_MEMORY;
2030   }
2031 
2032   // Iterate over all the modules loaded to the system.
2033   ClassLoaderDataGraph::modules_do(&do_module);
2034 
2035   jint len = _tbl->length();
2036   guarantee(len > 0, "at least one module must be present");
2037 
2038   jobject* array = (jobject*)env->jvmtiMalloc((jlong)(len * sizeof(jobject)));
2039   if (array == NULL) {
2040     return JVMTI_ERROR_OUT_OF_MEMORY;
2041   }
2042   for (jint idx = 0; idx < len; idx++) {
2043     array[idx] = JNIHandles::make_local(_tbl->at(idx).resolve());
2044   }
2045   _tbl = NULL;
2046   *modules_ptr = array;
2047   *module_count_ptr = len;
2048   return JVMTI_ERROR_NONE;
2049 }
2050 
2051 void
2052 UpdateForPopTopFrameClosure::doit(Thread *target, bool self) {
2053   Thread* current_thread  = Thread::current();
2054   HandleMark hm(current_thread);
2055   JavaThread* java_thread = JavaThread::cast(target);
2056 
2057   if (java_thread->is_exiting()) {
2058     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2059   }
2060   assert(java_thread == _state->get_thread(), "Must be");
2061 
2062   if (!self && !java_thread->is_suspended() && !java_thread->is_thread_suspended()) {
2063     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2064     return;
2065   }
2066 
2067   // Check to see if a PopFrame was already in progress
2068   if (java_thread->popframe_condition() != JavaThread::popframe_inactive) {
2069     // Probably possible for JVMTI clients to trigger this, but the
2070     // JPDA backend shouldn't allow this to happen
2071     _result = JVMTI_ERROR_INTERNAL;
2072     return;
2073   }
2074 
2075   // Was workaround bug
2076   //    4812902: popFrame hangs if the method is waiting at a synchronize
2077   // Catch this condition and return an error to avoid hanging.
2078   // Now JVMTI spec allows an implementation to bail out with an opaque frame error.
2079   OSThread* osThread = java_thread->osthread();
2080   if (osThread->get_state() == MONITOR_WAIT) {
2081     _result = JVMTI_ERROR_OPAQUE_FRAME;
2082     return;
2083   }
2084 
2085   ResourceMark rm(current_thread);
2086   // Check if there is more than one Java frame in this thread, that the top two frames
2087   // are Java (not native) frames, and that there is no intervening VM frame
2088   int frame_count = 0;
2089   bool is_interpreted[2];
2090   intptr_t *frame_sp[2];
2091   // The 2-nd arg of constructor is needed to stop iterating at java entry frame.
2092   for (vframeStream vfs(java_thread, true, false /* process_frames */); !vfs.at_end(); vfs.next()) {
2093     methodHandle mh(current_thread, vfs.method());
2094     if (mh->is_native()) {
2095       _result = JVMTI_ERROR_OPAQUE_FRAME;
2096       return;
2097     }
2098     is_interpreted[frame_count] = vfs.is_interpreted_frame();
2099     frame_sp[frame_count] = vfs.frame_id();
2100     if (++frame_count > 1) break;
2101   }
2102   if (frame_count < 2)  {
2103     // We haven't found two adjacent non-native Java frames on the top.
2104     // There can be two situations here:
2105     //  1. There are no more java frames
2106     //  2. Two top java frames are separated by non-java native frames
2107     if(JvmtiEnvBase::vframeForNoProcess(java_thread, 1) == NULL) {
2108       _result = JVMTI_ERROR_NO_MORE_FRAMES;
2109       return;
2110     } else {
2111       // Intervening non-java native or VM frames separate java frames.
2112       // Current implementation does not support this. See bug #5031735.
2113       // In theory it is possible to pop frames in such cases.
2114       _result = JVMTI_ERROR_OPAQUE_FRAME;
2115       return;
2116     }
2117   }
2118 
2119   // If any of the top 2 frames is a compiled one, need to deoptimize it
2120   for (int i = 0; i < 2; i++) {
2121     if (!is_interpreted[i]) {
2122       Deoptimization::deoptimize_frame(java_thread, frame_sp[i]);
2123     }
2124   }
2125 
2126   // Update the thread state to reflect that the top frame is popped
2127   // so that cur_stack_depth is maintained properly and all frameIDs
2128   // are invalidated.
2129   // The current frame will be popped later when the suspended thread
2130   // is resumed and right before returning from VM to Java.
2131   // (see call_VM_base() in assembler_<cpu>.cpp).
2132 
2133   // It's fine to update the thread state here because no JVMTI events
2134   // shall be posted for this PopFrame.
2135 
2136   _state->update_for_pop_top_frame();
2137   java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
2138   // Set pending step flag for this popframe and it is cleared when next
2139   // step event is posted.
2140   _state->set_pending_step_for_popframe();
2141   _result = JVMTI_ERROR_NONE;
2142 }
2143 
2144 void
2145 SetFramePopClosure::doit(Thread *target, bool self) {
2146   ResourceMark rm;
2147   JavaThread* java_thread = JavaThread::cast(target);
2148 
2149   if (java_thread->is_exiting()) {
2150     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2151   }
2152 
2153   // TBD: This might need to be corrected for detached carrier and virtual threads.
2154   assert(_state->get_thread_or_saved() == java_thread, "Must be");
2155 
2156   if (!self && !java_thread->is_suspended()) {
2157     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2158     return;
2159   }
2160 
2161   vframe *vf = JvmtiEnvBase::vframeForNoProcess(java_thread, _depth);
2162   if (vf == NULL) {
2163     _result = JVMTI_ERROR_NO_MORE_FRAMES;
2164     return;
2165   }
2166   vf = JvmtiEnvBase::check_and_skip_hidden_frames(java_thread, (javaVFrame*)vf);
2167   if (!vf->is_java_frame() || ((javaVFrame*) vf)->method()->is_native()) {
2168     _result = JVMTI_ERROR_OPAQUE_FRAME;
2169     return;
2170   }
2171 
2172   assert(vf->frame_pointer() != NULL, "frame pointer mustn't be NULL");
2173   int frame_number = _state->count_frames() - _depth;
2174   _state->env_thread_state((JvmtiEnvBase*)_env)->set_frame_pop(frame_number);
2175   _result = JVMTI_ERROR_NONE;
2176 }
2177 
2178 void
2179 GetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2180   JavaThread *jt = JavaThread::cast(target);
2181   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
2182     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread,
2183                                                          jt,
2184                                                          _owned_monitors_list);
2185   }
2186 }
2187 
2188 void
2189 GetCurrentContendedMonitorClosure::do_thread(Thread *target) {
2190   JavaThread *jt = JavaThread::cast(target);
2191   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
2192     _result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor(_calling_thread,
2193                                                                     jt,
2194                                                                     _owned_monitor_ptr,
2195                                                                     _is_virtual);
2196   }
2197 }
2198 
2199 void
2200 VM_VThreadGetStackTrace::doit() {
2201   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2202     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2203     return;
2204   }
2205   ResourceMark rm;
2206   javaVFrame* jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2207 
2208   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2209                                                     _start_depth, _max_count,
2210                                                     _frame_buffer, _count_ptr);
2211 }
2212 
2213 void
2214 GetStackTraceClosure::do_thread(Thread *target) {
2215   JavaThread *jt = JavaThread::cast(target);
2216   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2217     _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jt,
2218                                                       _start_depth, _max_count,
2219                                                       _frame_buffer, _count_ptr);
2220   }
2221 }
2222 
2223 #ifdef ASSERT
2224 void
2225 PrintStackTraceClosure::do_thread_impl(Thread *target) {
2226   JavaThread *java_thread = JavaThread::cast(target);
2227   Thread *current_thread = Thread::current();
2228 
2229   ResourceMark rm (current_thread);
2230   const char* tname = JvmtiTrace::safe_get_thread_name(java_thread);
2231   oop t_oop = java_thread->mounted_vthread();
2232   t_oop = t_oop == NULL ? java_thread->threadObj() : t_oop;
2233   bool is_vt_suspended = java_lang_VirtualThread::is_instance(t_oop) && JvmtiVTSuspender::is_vthread_suspended(t_oop);
2234 
2235   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",
2236                 tname, java_thread->name(), java_thread->is_exiting(),
2237                 java_thread->is_suspended(), java_thread->is_thread_suspended(), is_vt_suspended,
2238                 java_thread->is_VTMT_disabler(), java_thread->is_in_VTMT());
2239 
2240   if (java_thread->has_last_Java_frame()) {
2241     RegisterMap reg_map(java_thread, true, true);
2242     ResourceMark rm(current_thread);
2243     HandleMark hm(current_thread);
2244     javaVFrame *jvf = JvmtiEnvBase::get_last_java_vframe(java_thread, &reg_map);
2245     while (jvf != NULL) {
2246       tty->print_cr("  %s:%d",
2247                     jvf->method()->external_name(),
2248                     jvf->method()->line_number_from_bci(jvf->bci()));
2249       jvf = jvf->java_sender();
2250     }
2251   }
2252   tty->print_cr("");
2253 }
2254 
2255 void
2256 PrintStackTraceClosure::do_thread(Thread *target) {
2257   JavaThread *java_thread = JavaThread::cast(target);
2258   Thread *current_thread = Thread::current();
2259 
2260   assert(SafepointSynchronize::is_at_safepoint() ||
2261       java_thread->is_handshake_safe_for(current_thread),
2262          "call by myself / at safepoint / at handshake");
2263 
2264   PrintStackTraceClosure::do_thread_impl(target);
2265 }
2266 #endif
2267 
2268 void
2269 VM_VThreadGetFrameCount::doit() {
2270   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2271 }
2272 
2273 void
2274 GetFrameCountClosure::do_thread(Thread *target) {
2275   JavaThread* jt = JavaThread::cast(target);
2276   assert(target == jt, "just checking");
2277   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2278     _result = ((JvmtiEnvBase*)_env)->get_frame_count(jt, _count_ptr);
2279   }
2280 }
2281 
2282 void
2283 GetFrameLocationClosure::do_thread(Thread *target) {
2284   JavaThread *jt = JavaThread::cast(target);
2285   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2286     _result = ((JvmtiEnvBase*)_env)->get_frame_location(jt, _depth,
2287                                                         _method_ptr, _location_ptr);
2288   }
2289 }
2290 
2291 void
2292 VThreadGetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2293   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2294     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2295     return;
2296   }
2297   JavaThread* java_thread = JavaThread::cast(target);
2298   Thread* cur_thread = Thread::current();
2299   ResourceMark rm(cur_thread);
2300   HandleMark hm(cur_thread);
2301 
2302   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2303 
2304   if (!java_thread->is_exiting() && java_thread->threadObj() != NULL) {
2305     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors((JavaThread*)target,
2306                                                          java_thread,
2307                                                          jvf,
2308                                                          _owned_monitors_list);
2309   }
2310 }
2311 
2312 void
2313 VThreadGetThreadClosure::do_thread(Thread *target) {
2314   assert(target->is_Java_thread(), "just checking");
2315   JavaThread *jt = JavaThread::cast(target);
2316   oop carrier_thread = java_lang_VirtualThread::carrier_thread(_vthread_h());
2317   *_carrier_thread_ptr = (jthread)JNIHandles::make_local(jt, carrier_thread);
2318 }
2319 
2320 void
2321 VThreadGetStackTraceClosure::do_thread(Thread *target) {
2322   assert(target->is_Java_thread(), "just checking");
2323   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2324     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2325     return;
2326   }
2327   Thread* cur_thread = Thread::current();
2328   ResourceMark rm(cur_thread);
2329   HandleMark hm(cur_thread);
2330 
2331   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2332   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2333                                                     _start_depth, _max_count,
2334                                                     _frame_buffer, _count_ptr);
2335 }
2336 
2337 void
2338 VThreadGetFrameCountClosure::do_thread(Thread *target) {
2339   assert(target->is_Java_thread(), "just checking");
2340   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2341 }
2342 
2343 void
2344 VThreadGetFrameLocationClosure::do_thread(Thread *target) {
2345   assert(target->is_Java_thread(), "just checking");
2346   _result = ((JvmtiEnvBase*)_env)->get_frame_location(_vthread_h(), _depth,
2347                                                       _method_ptr, _location_ptr);
2348 }
2349 
2350 void
2351 VThreadGetThreadStateClosure::do_thread(Thread *target) {
2352   assert(target->is_Java_thread(), "just checking");
2353   jshort vthread_state = java_lang_VirtualThread::state(_vthread_h());
2354   oop carrier_thread_oop = java_lang_VirtualThread::carrier_thread(_vthread_h());
2355   jint state;
2356 
2357   if (vthread_state == java_lang_VirtualThread::RUNNING && carrier_thread_oop != NULL) {
2358     state = (jint) java_lang_Thread::get_thread_status(carrier_thread_oop);
2359     JavaThread* java_thread = java_lang_Thread::thread(carrier_thread_oop);
2360     if (java_thread->is_suspended()) {
2361       state |= JVMTI_THREAD_STATE_SUSPENDED;
2362     }
2363   } else {
2364     state = (jint) java_lang_VirtualThread::map_state_to_thread_status(vthread_state);
2365   }
2366   if (java_lang_Thread::interrupted(_vthread_h())) {
2367     state |= JVMTI_THREAD_STATE_INTERRUPTED;
2368   }
2369   *_state_ptr = state;
2370   _result = JVMTI_ERROR_NONE;
2371 }