1 /*
   2  * Copyright (c) 2003, 2022, 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.inline.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/continuationEntry.inline.hpp"
  45 #include "runtime/deoptimization.hpp"
  46 #include "runtime/frame.inline.hpp"
  47 #include "runtime/handles.inline.hpp"
  48 #include "runtime/interfaceSupport.inline.hpp"
  49 #include "runtime/javaThread.inline.hpp"
  50 #include "runtime/jfieldIDWorkaround.hpp"
  51 #include "runtime/jniHandles.inline.hpp"
  52 #include "runtime/objectMonitor.inline.hpp"
  53 #include "runtime/osThread.hpp"
  54 #include "runtime/signature.hpp"
  55 #include "runtime/threads.hpp"
  56 #include "runtime/threadSMR.hpp"
  57 #include "runtime/vframe.inline.hpp"
  58 #include "runtime/vframe_hp.hpp"
  59 #include "runtime/vmThread.hpp"
  60 #include "runtime/vmOperations.hpp"
  61 #include "services/threadService.hpp"
  62 
  63 
  64 ///////////////////////////////////////////////////////////////
  65 //
  66 // JvmtiEnvBase
  67 //
  68 
  69 JvmtiEnvBase* JvmtiEnvBase::_head_environment = NULL;
  70 
  71 bool JvmtiEnvBase::_globally_initialized = false;
  72 volatile bool JvmtiEnvBase::_needs_clean_up = false;
  73 
  74 jvmtiPhase JvmtiEnvBase::_phase = JVMTI_PHASE_PRIMORDIAL;
  75 
  76 volatile int JvmtiEnvBase::_dying_thread_env_iteration_count = 0;
  77 
  78 extern jvmtiInterface_1_ jvmti_Interface;
  79 extern jvmtiInterface_1_ jvmtiTrace_Interface;
  80 
  81 
  82 // perform initializations that must occur before any JVMTI environments
  83 // are released but which should only be initialized once (no matter
  84 // how many environments are created).
  85 void
  86 JvmtiEnvBase::globally_initialize() {
  87   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
  88   assert(_globally_initialized == false, "bad call");
  89 
  90   JvmtiManageCapabilities::initialize();
  91 
  92   // register extension functions and events
  93   JvmtiExtensions::register_extensions();
  94 
  95 #ifdef JVMTI_TRACE
  96   JvmtiTrace::initialize();
  97 #endif
  98 
  99   _globally_initialized = true;
 100 }
 101 
 102 
 103 void
 104 JvmtiEnvBase::initialize() {
 105   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 106 
 107   // Add this environment to the end of the environment list (order is important)
 108   {
 109     // This block of code must not contain any safepoints, as list deallocation
 110     // (which occurs at a safepoint) cannot occur simultaneously with this list
 111     // addition.  Note: NoSafepointVerifier cannot, currently, be used before
 112     // threads exist.
 113     JvmtiEnvIterator it;
 114     JvmtiEnvBase *previous_env = NULL;
 115     for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
 116       previous_env = env;
 117     }
 118     if (previous_env == NULL) {
 119       _head_environment = this;
 120     } else {
 121       previous_env->set_next_environment(this);
 122     }
 123   }
 124 
 125   if (_globally_initialized == false) {
 126     globally_initialize();
 127   }
 128 }
 129 
 130 jvmtiPhase
 131 JvmtiEnvBase::phase() {
 132   // For the JVMTI environments possessed the can_generate_early_vmstart:
 133   //   replace JVMTI_PHASE_PRIMORDIAL with JVMTI_PHASE_START
 134   if (_phase == JVMTI_PHASE_PRIMORDIAL &&
 135       JvmtiExport::early_vmstart_recorded() &&
 136       early_vmstart_env()) {
 137     return JVMTI_PHASE_START;
 138   }
 139   return _phase; // Normal case
 140 }
 141 
 142 bool
 143 JvmtiEnvBase::is_valid() {
 144   jint value = 0;
 145 
 146   // This object might not be a JvmtiEnvBase so we can't assume
 147   // the _magic field is properly aligned. Get the value in a safe
 148   // way and then check against JVMTI_MAGIC.
 149 
 150   switch (sizeof(_magic)) {
 151   case 2:
 152     value = Bytes::get_native_u2((address)&_magic);
 153     break;
 154 
 155   case 4:
 156     value = Bytes::get_native_u4((address)&_magic);
 157     break;
 158 
 159   case 8:
 160     value = Bytes::get_native_u8((address)&_magic);
 161     break;
 162 
 163   default:
 164     guarantee(false, "_magic field is an unexpected size");
 165   }
 166 
 167   return value == JVMTI_MAGIC;
 168 }
 169 
 170 
 171 bool
 172 JvmtiEnvBase::use_version_1_0_semantics() {
 173   int major, minor, micro;
 174 
 175   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 176   return major == 1 && minor == 0;  // micro version doesn't matter here
 177 }
 178 
 179 
 180 bool
 181 JvmtiEnvBase::use_version_1_1_semantics() {
 182   int major, minor, micro;
 183 
 184   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 185   return major == 1 && minor == 1;  // micro version doesn't matter here
 186 }
 187 
 188 bool
 189 JvmtiEnvBase::use_version_1_2_semantics() {
 190   int major, minor, micro;
 191 
 192   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 193   return major == 1 && minor == 2;  // micro version doesn't matter here
 194 }
 195 
 196 
 197 JvmtiEnvBase::JvmtiEnvBase(jint version) : _env_event_enable() {
 198   _version = version;
 199   _env_local_storage = NULL;
 200   _tag_map = NULL;
 201   _native_method_prefix_count = 0;
 202   _native_method_prefixes = NULL;
 203   _next = NULL;
 204   _class_file_load_hook_ever_enabled = false;
 205 
 206   // Moot since ClassFileLoadHook not yet enabled.
 207   // But "true" will give a more predictable ClassFileLoadHook behavior
 208   // for environment creation during ClassFileLoadHook.
 209   _is_retransformable = true;
 210 
 211   // all callbacks initially NULL
 212   memset(&_event_callbacks,0,sizeof(jvmtiEventCallbacks));
 213 
 214   // all capabilities initially off
 215   memset(&_current_capabilities, 0, sizeof(_current_capabilities));
 216 
 217   // all prohibited capabilities initially off
 218   memset(&_prohibited_capabilities, 0, sizeof(_prohibited_capabilities));
 219 
 220   _magic = JVMTI_MAGIC;
 221 
 222   JvmtiEventController::env_initialize((JvmtiEnv*)this);
 223 
 224 #ifdef JVMTI_TRACE
 225   _jvmti_external.functions = TraceJVMTI != NULL ? &jvmtiTrace_Interface : &jvmti_Interface;
 226 #else
 227   _jvmti_external.functions = &jvmti_Interface;
 228 #endif
 229 }
 230 
 231 
 232 void
 233 JvmtiEnvBase::dispose() {
 234 
 235 #ifdef JVMTI_TRACE
 236   JvmtiTrace::shutdown();
 237 #endif
 238 
 239   // Dispose of event info and let the event controller call us back
 240   // in a locked state (env_dispose, below)
 241   JvmtiEventController::env_dispose(this);
 242 }
 243 
 244 void
 245 JvmtiEnvBase::env_dispose() {
 246   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 247 
 248   // We have been entered with all events disabled on this environment.
 249   // A race to re-enable events (by setting callbacks) is prevented by
 250   // checking for a valid environment when setting callbacks (while
 251   // holding the JvmtiThreadState_lock).
 252 
 253   // Mark as invalid.
 254   _magic = DISPOSED_MAGIC;
 255 
 256   // Relinquish all capabilities.
 257   jvmtiCapabilities *caps = get_capabilities();
 258   JvmtiManageCapabilities::relinquish_capabilities(caps, caps, caps);
 259 
 260   // Same situation as with events (see above)
 261   set_native_method_prefixes(0, NULL);
 262 
 263   JvmtiTagMap* tag_map_to_clear = tag_map_acquire();
 264   // A tag map can be big, clear it now to save memory until
 265   // the destructor runs.
 266   if (tag_map_to_clear != NULL) {
 267     tag_map_to_clear->clear();
 268   }
 269 
 270   _needs_clean_up = true;
 271 }
 272 
 273 
 274 JvmtiEnvBase::~JvmtiEnvBase() {
 275   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 276 
 277   // There is a small window of time during which the tag map of a
 278   // disposed environment could have been reallocated.
 279   // Make sure it is gone.
 280   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
 281   set_tag_map(NULL);
 282   // A tag map can be big, deallocate it now
 283   if (tag_map_to_deallocate != NULL) {
 284     delete tag_map_to_deallocate;
 285   }
 286 
 287   _magic = BAD_MAGIC;
 288 }
 289 
 290 
 291 void
 292 JvmtiEnvBase::periodic_clean_up() {
 293   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 294 
 295   // JvmtiEnvBase reference is saved in JvmtiEnvThreadState. So
 296   // clean up JvmtiThreadState before deleting JvmtiEnv pointer.
 297   JvmtiThreadState::periodic_clean_up();
 298 
 299   // Unlink all invalid environments from the list of environments
 300   // and deallocate them
 301   JvmtiEnvIterator it;
 302   JvmtiEnvBase* previous_env = NULL;
 303   JvmtiEnvBase* env = it.first();
 304   while (env != NULL) {
 305     if (env->is_valid()) {
 306       previous_env = env;
 307       env = it.next(env);
 308     } else {
 309       // This one isn't valid, remove it from the list and deallocate it
 310       JvmtiEnvBase* defunct_env = env;
 311       env = it.next(env);
 312       if (previous_env == NULL) {
 313         _head_environment = env;
 314       } else {
 315         previous_env->set_next_environment(env);
 316       }
 317       delete defunct_env;
 318     }
 319   }
 320 
 321 }
 322 
 323 
 324 void
 325 JvmtiEnvBase::check_for_periodic_clean_up() {
 326   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 327 
 328   class ThreadInsideIterationClosure: public ThreadClosure {
 329    private:
 330     bool _inside;
 331    public:
 332     ThreadInsideIterationClosure() : _inside(false) {};
 333 
 334     void do_thread(Thread* thread) {
 335       _inside |= thread->is_inside_jvmti_env_iteration();
 336     }
 337 
 338     bool is_inside_jvmti_env_iteration() {
 339       return _inside;
 340     }
 341   };
 342 
 343   if (_needs_clean_up) {
 344     // Check if we are currently iterating environment,
 345     // deallocation should not occur if we are
 346     ThreadInsideIterationClosure tiic;
 347     Threads::threads_do(&tiic);
 348     if (!tiic.is_inside_jvmti_env_iteration() &&
 349              !is_inside_dying_thread_env_iteration()) {
 350       _needs_clean_up = false;
 351       JvmtiEnvBase::periodic_clean_up();
 352     }
 353   }
 354 }
 355 
 356 
 357 void
 358 JvmtiEnvBase::record_first_time_class_file_load_hook_enabled() {
 359   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
 360          "sanity check");
 361 
 362   if (!_class_file_load_hook_ever_enabled) {
 363     _class_file_load_hook_ever_enabled = true;
 364 
 365     if (get_capabilities()->can_retransform_classes) {
 366       _is_retransformable = true;
 367     } else {
 368       _is_retransformable = false;
 369 
 370       // cannot add retransform capability after ClassFileLoadHook has been enabled
 371       get_prohibited_capabilities()->can_retransform_classes = 1;
 372     }
 373   }
 374 }
 375 
 376 
 377 void
 378 JvmtiEnvBase::record_class_file_load_hook_enabled() {
 379   if (!_class_file_load_hook_ever_enabled) {
 380     if (Threads::number_of_threads() == 0) {
 381       record_first_time_class_file_load_hook_enabled();
 382     } else {
 383       MutexLocker mu(JvmtiThreadState_lock);
 384       record_first_time_class_file_load_hook_enabled();
 385     }
 386   }
 387 }
 388 
 389 
 390 jvmtiError
 391 JvmtiEnvBase::set_native_method_prefixes(jint prefix_count, char** prefixes) {
 392   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
 393          "sanity check");
 394 
 395   int old_prefix_count = get_native_method_prefix_count();
 396   char **old_prefixes = get_native_method_prefixes();
 397 
 398   // allocate and install the new prefixex
 399   if (prefix_count == 0 || !is_valid()) {
 400     _native_method_prefix_count = 0;
 401     _native_method_prefixes = NULL;
 402   } else {
 403     // there are prefixes, allocate an array to hold them, and fill it
 404     char** new_prefixes = (char**)os::malloc((prefix_count) * sizeof(char*), mtInternal);
 405     if (new_prefixes == NULL) {
 406       return JVMTI_ERROR_OUT_OF_MEMORY;
 407     }
 408     for (int i = 0; i < prefix_count; i++) {
 409       char* prefix = prefixes[i];
 410       if (prefix == NULL) {
 411         for (int j = 0; j < (i-1); j++) {
 412           os::free(new_prefixes[j]);
 413         }
 414         os::free(new_prefixes);
 415         return JVMTI_ERROR_NULL_POINTER;
 416       }
 417       prefix = os::strdup(prefixes[i]);
 418       if (prefix == NULL) {
 419         for (int j = 0; j < (i-1); j++) {
 420           os::free(new_prefixes[j]);
 421         }
 422         os::free(new_prefixes);
 423         return JVMTI_ERROR_OUT_OF_MEMORY;
 424       }
 425       new_prefixes[i] = prefix;
 426     }
 427     _native_method_prefix_count = prefix_count;
 428     _native_method_prefixes = new_prefixes;
 429   }
 430 
 431   // now that we know the new prefixes have been successfully installed we can
 432   // safely remove the old ones
 433   if (old_prefix_count != 0) {
 434     for (int i = 0; i < old_prefix_count; i++) {
 435       os::free(old_prefixes[i]);
 436     }
 437     os::free(old_prefixes);
 438   }
 439 
 440   return JVMTI_ERROR_NONE;
 441 }
 442 
 443 
 444 // Collect all the prefixes which have been set in any JVM TI environments
 445 // by the SetNativeMethodPrefix(es) functions.  Be sure to maintain the
 446 // order of environments and the order of prefixes within each environment.
 447 // Return in a resource allocated array.
 448 char**
 449 JvmtiEnvBase::get_all_native_method_prefixes(int* count_ptr) {
 450   assert(Threads::number_of_threads() == 0 ||
 451          SafepointSynchronize::is_at_safepoint() ||
 452          JvmtiThreadState_lock->is_locked(),
 453          "sanity check");
 454 
 455   int total_count = 0;
 456   GrowableArray<char*>* prefix_array =new GrowableArray<char*>(5);
 457 
 458   JvmtiEnvIterator it;
 459   for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
 460     int prefix_count = env->get_native_method_prefix_count();
 461     char** prefixes = env->get_native_method_prefixes();
 462     for (int j = 0; j < prefix_count; j++) {
 463       // retrieve a prefix and so that it is safe against asynchronous changes
 464       // copy it into the resource area
 465       char* prefix = prefixes[j];
 466       char* prefix_copy = NEW_RESOURCE_ARRAY(char, strlen(prefix)+1);
 467       strcpy(prefix_copy, prefix);
 468       prefix_array->at_put_grow(total_count++, prefix_copy);
 469     }
 470   }
 471 
 472   char** all_prefixes = NEW_RESOURCE_ARRAY(char*, total_count);
 473   char** p = all_prefixes;
 474   for (int i = 0; i < total_count; ++i) {
 475     *p++ = prefix_array->at(i);
 476   }
 477   *count_ptr = total_count;
 478   return all_prefixes;
 479 }
 480 
 481 void
 482 JvmtiEnvBase::set_event_callbacks(const jvmtiEventCallbacks* callbacks,
 483                                                jint size_of_callbacks) {
 484   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 485 
 486   size_t byte_cnt = sizeof(jvmtiEventCallbacks);
 487 
 488   // clear in either case to be sure we got any gap between sizes
 489   memset(&_event_callbacks, 0, byte_cnt);
 490 
 491   // Now that JvmtiThreadState_lock is held, prevent a possible race condition where events
 492   // are re-enabled by a call to set event callbacks where the DisposeEnvironment
 493   // occurs after the boiler-plate environment check and before the lock is acquired.
 494   if (callbacks != NULL && is_valid()) {
 495     if (size_of_callbacks < (jint)byte_cnt) {
 496       byte_cnt = size_of_callbacks;
 497     }
 498     memcpy(&_event_callbacks, callbacks, byte_cnt);
 499   }
 500 }
 501 
 502 
 503 // In the fullness of time, all users of the method should instead
 504 // directly use allocate, besides being cleaner and faster, this will
 505 // mean much better out of memory handling
 506 unsigned char *
 507 JvmtiEnvBase::jvmtiMalloc(jlong size) {
 508   unsigned char* mem = NULL;
 509   jvmtiError result = allocate(size, &mem);
 510   assert(result == JVMTI_ERROR_NONE, "Allocate failed");
 511   return mem;
 512 }
 513 
 514 
 515 // Handle management
 516 
 517 jobject JvmtiEnvBase::jni_reference(Handle hndl) {
 518   return JNIHandles::make_local(hndl());
 519 }
 520 
 521 jobject JvmtiEnvBase::jni_reference(JavaThread *thread, Handle hndl) {
 522   return JNIHandles::make_local(thread, hndl());
 523 }
 524 
 525 void JvmtiEnvBase::destroy_jni_reference(jobject jobj) {
 526   JNIHandles::destroy_local(jobj);
 527 }
 528 
 529 void JvmtiEnvBase::destroy_jni_reference(JavaThread *thread, jobject jobj) {
 530   JNIHandles::destroy_local(jobj); // thread is unused.
 531 }
 532 
 533 //
 534 // Threads
 535 //
 536 
 537 jobject *
 538 JvmtiEnvBase::new_jobjectArray(int length, Handle *handles) {
 539   if (length == 0) {
 540     return NULL;
 541   }
 542 
 543   jobject *objArray = (jobject *) jvmtiMalloc(sizeof(jobject) * length);
 544   NULL_CHECK(objArray, NULL);
 545 
 546   for (int i=0; i<length; i++) {
 547     objArray[i] = jni_reference(handles[i]);
 548   }
 549   return objArray;
 550 }
 551 
 552 jthread *
 553 JvmtiEnvBase::new_jthreadArray(int length, Handle *handles) {
 554   return (jthread *) new_jobjectArray(length,handles);
 555 }
 556 
 557 jthreadGroup *
 558 JvmtiEnvBase::new_jthreadGroupArray(int length, Handle *handles) {
 559   return (jthreadGroup *) new_jobjectArray(length,handles);
 560 }
 561 
 562 // Return the vframe on the specified thread and depth, NULL if no such frame.
 563 // The thread and the oops in the returned vframe might not have been processed.
 564 javaVFrame*
 565 JvmtiEnvBase::jvf_for_thread_and_depth(JavaThread* java_thread, jint depth) {
 566   if (!java_thread->has_last_Java_frame()) {
 567     return NULL;
 568   }
 569   RegisterMap reg_map(java_thread,
 570                       RegisterMap::UpdateMap::include,
 571                       RegisterMap::ProcessFrames::skip,
 572                       RegisterMap::WalkContinuation::include);
 573   javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
 574 
 575   jvf = JvmtiEnvBase::check_and_skip_hidden_frames(java_thread, jvf);
 576 
 577   for (int d = 0; jvf != NULL && d < depth; d++) {
 578     jvf = jvf->java_sender();
 579   }
 580   return jvf;
 581 }
 582 
 583 //
 584 // utilities: JNI objects
 585 //
 586 
 587 
 588 jclass
 589 JvmtiEnvBase::get_jni_class_non_null(Klass* k) {
 590   assert(k != NULL, "k != NULL");
 591   Thread *thread = Thread::current();
 592   return (jclass)jni_reference(Handle(thread, k->java_mirror()));
 593 }
 594 
 595 //
 596 // Field Information
 597 //
 598 
 599 bool
 600 JvmtiEnvBase::get_field_descriptor(Klass* k, jfieldID field, fieldDescriptor* fd) {
 601   if (!jfieldIDWorkaround::is_valid_jfieldID(k, field)) {
 602     return false;
 603   }
 604   bool found = false;
 605   if (jfieldIDWorkaround::is_static_jfieldID(field)) {
 606     JNIid* id = jfieldIDWorkaround::from_static_jfieldID(field);
 607     found = id->find_local_field(fd);
 608   } else {
 609     // Non-static field. The fieldID is really the offset of the field within the object.
 610     int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);
 611     found = InstanceKlass::cast(k)->find_field_from_offset(offset, false, fd);
 612   }
 613   return found;
 614 }
 615 
 616 bool
 617 JvmtiEnvBase::is_vthread_alive(oop vt) {
 618   return java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::NEW &&
 619          java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::TERMINATED;
 620 }
 621 
 622 // Return JavaThread if virtual thread is mounted, NULL otherwise.
 623 JavaThread* JvmtiEnvBase::get_JavaThread_or_null(oop vthread) {
 624   oop carrier_thread = java_lang_VirtualThread::carrier_thread(vthread);
 625   if (carrier_thread == NULL) {
 626     return NULL;
 627   }
 628 
 629   JavaThread* java_thread = java_lang_Thread::thread(carrier_thread);
 630   oop cont = java_lang_VirtualThread::continuation(vthread);
 631   assert(cont != NULL, "must be");
 632   assert(Continuation::continuation_scope(cont) == java_lang_VirtualThread::vthread_scope(), "must be");
 633   return Continuation::is_continuation_mounted(java_thread, cont) ? java_thread : NULL;
 634 }
 635 
 636 javaVFrame*
 637 JvmtiEnvBase::check_and_skip_hidden_frames(bool is_in_VTMS_transition, javaVFrame* jvf) {
 638   // The second condition is needed to hide notification methods.
 639   if (!is_in_VTMS_transition && (jvf == NULL || !jvf->method()->jvmti_mount_transition())) {
 640     return jvf;  // No frames to skip.
 641   }
 642   // Find jvf with a method annotated with @JvmtiMountTransition.
 643   for ( ; jvf != NULL; jvf = jvf->java_sender()) {
 644     if (jvf->method()->jvmti_mount_transition()) {  // Cannot actually appear in an unmounted continuation; they're never frozen.
 645       jvf = jvf->java_sender();  // Skip annotated method.
 646       break;
 647     }
 648     if (jvf->method()->changes_current_thread()) {
 649       break;
 650     }
 651     // Skip frame above annotated method.
 652   }
 653   return jvf;
 654 }
 655 
 656 javaVFrame*
 657 JvmtiEnvBase::check_and_skip_hidden_frames(JavaThread* jt, javaVFrame* jvf) {
 658   jvf = check_and_skip_hidden_frames(jt->is_in_VTMS_transition(), jvf);
 659   return jvf;
 660 }
 661 
 662 javaVFrame*
 663 JvmtiEnvBase::check_and_skip_hidden_frames(oop vthread, javaVFrame* jvf) {
 664   JvmtiThreadState* state = java_lang_Thread::jvmti_thread_state(vthread);
 665   if (state == NULL) {
 666     // nothing to skip
 667     return jvf;
 668   }
 669   jvf = check_and_skip_hidden_frames(state->is_in_VTMS_transition(), jvf);
 670   return jvf;
 671 }
 672 
 673 javaVFrame*
 674 JvmtiEnvBase::get_vthread_jvf(oop vthread) {
 675   assert(java_lang_VirtualThread::state(vthread) != java_lang_VirtualThread::NEW, "sanity check");
 676   assert(java_lang_VirtualThread::state(vthread) != java_lang_VirtualThread::TERMINATED, "sanity check");
 677 
 678   Thread* cur_thread = Thread::current();
 679   oop cont = java_lang_VirtualThread::continuation(vthread);
 680   javaVFrame* jvf = NULL;
 681 
 682   JavaThread* java_thread = get_JavaThread_or_null(vthread);
 683   if (java_thread != NULL) {
 684     if (!java_thread->has_last_Java_frame()) {
 685       // TBD: This is a temporary work around to avoid a guarantee caused by
 686       // the native enterSpecial frame on the top. No frames will be found
 687       // by the JVMTI functions such as GetStackTrace.
 688       return NULL;
 689     }
 690     vframeStream vfs(java_thread);
 691     jvf = vfs.at_end() ? NULL : vfs.asJavaVFrame();
 692     jvf = check_and_skip_hidden_frames(java_thread, jvf);
 693   } else {
 694     vframeStream vfs(cont);
 695     jvf = vfs.at_end() ? NULL : vfs.asJavaVFrame();
 696     jvf = check_and_skip_hidden_frames(vthread, jvf);
 697   }
 698   return jvf;
 699 }
 700 
 701 // Return correct javaVFrame for a carrier (non-virtual) thread.
 702 // It strips vthread frames at the top if there are any.
 703 javaVFrame*
 704 JvmtiEnvBase::get_cthread_last_java_vframe(JavaThread* jt, RegisterMap* reg_map_p) {
 705   // Strip vthread frames in case of carrier thread with mounted continuation.
 706   bool cthread_with_cont = JvmtiEnvBase::is_cthread_with_continuation(jt);
 707   javaVFrame *jvf = cthread_with_cont ? jt->carrier_last_java_vframe(reg_map_p)
 708                                       : jt->last_java_vframe(reg_map_p);
 709   // Skip hidden frames only for carrier threads
 710   // which are in non-temporary VTMS transition.
 711   if (jt->is_in_VTMS_transition()) {
 712     jvf = check_and_skip_hidden_frames(jt, jvf);
 713   }
 714   return jvf;
 715 }
 716 
 717 jint
 718 JvmtiEnvBase::get_thread_state(oop thread_oop, JavaThread* jt) {
 719   jint state = 0;
 720 
 721   if (thread_oop != NULL) {
 722     // Get most state bits.
 723     state = (jint)java_lang_Thread::get_thread_status(thread_oop);
 724   }
 725   if (jt != NULL) {
 726     // We have a JavaThread* so add more state bits.
 727     JavaThreadState jts = jt->thread_state();
 728 
 729     if (jt->is_carrier_thread_suspended() ||
 730         ((jt->jvmti_vthread() == NULL || jt->jvmti_vthread() == thread_oop) && jt->is_suspended())) {
 731       // Suspended non-virtual thread.
 732       state |= JVMTI_THREAD_STATE_SUSPENDED;
 733     }
 734     if (jts == _thread_in_native) {
 735       state |= JVMTI_THREAD_STATE_IN_NATIVE;
 736     }
 737     if (jt->is_interrupted(false)) {
 738       state |= JVMTI_THREAD_STATE_INTERRUPTED;
 739     }
 740   }
 741   return state;
 742 }
 743 
 744 jint
 745 JvmtiEnvBase::get_vthread_state(oop thread_oop, JavaThread* java_thread) {
 746   jint state = 0;
 747   bool ext_suspended = JvmtiVTSuspender::is_vthread_suspended(thread_oop);
 748   jint interrupted = java_lang_Thread::interrupted(thread_oop);
 749 
 750   if (java_thread != NULL) {
 751     // If virtual thread is blocked on a monitor enter the BLOCKED_ON_MONITOR_ENTER bit
 752     // is set for carrier thread instead of virtual.
 753     // Other state bits except filtered ones are expected to be the same.
 754     oop ct_oop = java_lang_VirtualThread::carrier_thread(thread_oop);
 755     jint filtered_bits = JVMTI_THREAD_STATE_SUSPENDED | JVMTI_THREAD_STATE_INTERRUPTED;
 756 
 757     // This call can trigger a safepoint, so thread_oop must not be used after it.
 758     state = get_thread_state(ct_oop, java_thread) & ~filtered_bits;
 759   } else {
 760     jshort vt_state = java_lang_VirtualThread::state(thread_oop);
 761     state = (jint)java_lang_VirtualThread::map_state_to_thread_status(vt_state);
 762   }
 763   if (ext_suspended && ((state & JVMTI_THREAD_STATE_ALIVE) != 0)) {
 764     state &= ~java_lang_VirtualThread::RUNNING;
 765     state |= JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE | JVMTI_THREAD_STATE_SUSPENDED;
 766   }
 767   if (interrupted) {
 768     state |= JVMTI_THREAD_STATE_INTERRUPTED;
 769   }
 770   return state;
 771 }
 772 
 773 jvmtiError
 774 JvmtiEnvBase::get_live_threads(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, Handle **thread_objs_p) {
 775   jint count = 0;
 776   Handle *thread_objs = NULL;
 777   ThreadsListEnumerator tle(current_thread, /* include_jvmti_agent_threads */ true);
 778   int nthreads = tle.num_threads();
 779   if (nthreads > 0) {
 780     thread_objs = NEW_RESOURCE_ARRAY_RETURN_NULL(Handle, nthreads);
 781     NULL_CHECK(thread_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 782     for (int i = 0; i < nthreads; i++) {
 783       Handle thread = tle.get_threadObj(i);
 784       if (thread()->is_a(vmClasses::Thread_klass()) && java_lang_Thread::threadGroup(thread()) == group_hdl()) {
 785         thread_objs[count++] = thread;
 786       }
 787     }
 788   }
 789   *thread_objs_p = thread_objs;
 790   *count_ptr = count;
 791   return JVMTI_ERROR_NONE;
 792 }
 793 
 794 jvmtiError
 795 JvmtiEnvBase::get_subgroups(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, Handle **group_objs_p) {
 796   ObjectLocker ol(group_hdl, current_thread);
 797 
 798   int ngroups = java_lang_ThreadGroup::ngroups(group_hdl());
 799   int nweaks = java_lang_ThreadGroup::nweaks(group_hdl());
 800 
 801   jint count = 0;
 802   Handle *group_objs = NULL;
 803   if (ngroups > 0 || nweaks > 0) {
 804     group_objs = NEW_RESOURCE_ARRAY_RETURN_NULL(Handle, ngroups + nweaks);
 805     NULL_CHECK(group_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 806 
 807     if (ngroups > 0) {
 808       // Strongly reachable subgroups:
 809       objArrayOop groups = java_lang_ThreadGroup::groups(group_hdl());
 810       for (int j = 0; j < ngroups; j++) {
 811         oop group_obj = groups->obj_at(j);
 812         assert(group_obj != NULL, "group_obj != NULL");
 813         group_objs[count++] = Handle(current_thread, group_obj);
 814       }
 815     }
 816 
 817     if (nweaks > 0) {
 818       // Weakly reachable subgroups:
 819       objArrayOop weaks = java_lang_ThreadGroup::weaks(group_hdl());
 820       for (int j = 0; j < nweaks; j++) {
 821         oop weak_obj = weaks->obj_at(j);
 822         assert(weak_obj != NULL, "weak_obj != NULL");
 823         oop group_obj = java_lang_ref_Reference::weak_referent(weak_obj);
 824         if (group_obj != NULL) {
 825           group_objs[count++] = Handle(current_thread, group_obj);
 826         }
 827       }
 828     }
 829   }
 830   *group_objs_p = group_objs;
 831   *count_ptr = count;
 832   return JVMTI_ERROR_NONE;
 833 }
 834 
 835 //
 836 // Object Monitor Information
 837 //
 838 
 839 //
 840 // Count the number of objects for a lightweight monitor. The hobj
 841 // parameter is object that owns the monitor so this routine will
 842 // count the number of times the same object was locked by frames
 843 // in java_thread.
 844 //
 845 jint
 846 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
 847   jint ret = 0;
 848   if (!java_thread->has_last_Java_frame()) {
 849     return ret;  // no Java frames so no monitors
 850   }
 851 
 852   Thread* current_thread = Thread::current();
 853   ResourceMark rm(current_thread);
 854   HandleMark   hm(current_thread);
 855   RegisterMap  reg_map(java_thread,
 856                        RegisterMap::UpdateMap::include,
 857                        RegisterMap::ProcessFrames::include,
 858                        RegisterMap::WalkContinuation::skip);
 859 
 860   for (javaVFrame *jvf = java_thread->last_java_vframe(&reg_map); jvf != NULL;
 861        jvf = jvf->java_sender()) {
 862     GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 863     if (!mons->is_empty()) {
 864       for (int i = 0; i < mons->length(); i++) {
 865         MonitorInfo *mi = mons->at(i);
 866         if (mi->owner_is_scalar_replaced()) continue;
 867 
 868         // see if owner of the monitor is our object
 869         if (mi->owner() != NULL && mi->owner() == hobj()) {
 870           ret++;
 871         }
 872       }
 873     }
 874   }
 875   return ret;
 876 }
 877 
 878 jvmtiError
 879 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread,
 880                                             jobject *monitor_ptr, bool is_virtual) {
 881   Thread *current_thread = Thread::current();
 882   assert(java_thread->is_handshake_safe_for(current_thread),
 883          "call by myself or at handshake");
 884   if (!is_virtual && JvmtiEnvBase::is_cthread_with_continuation(java_thread)) {
 885     // Carrier thread with a mounted continuation case.
 886     // No contended monitor can be owned by carrier thread in this case.
 887     *monitor_ptr = nullptr;
 888     return JVMTI_ERROR_NONE;
 889   }
 890   oop obj = NULL;
 891   // The ObjectMonitor* can't be async deflated since we are either
 892   // at a safepoint or the calling thread is operating on itself so
 893   // it cannot leave the underlying wait()/enter() call.
 894   ObjectMonitor *mon = java_thread->current_waiting_monitor();
 895   if (mon == NULL) {
 896     // thread is not doing an Object.wait() call
 897     mon = java_thread->current_pending_monitor();
 898     if (mon != NULL) {
 899       // The thread is trying to enter() an ObjectMonitor.
 900       obj = mon->object();
 901       assert(obj != NULL, "ObjectMonitor should have a valid object!");
 902     }
 903     // implied else: no contended ObjectMonitor
 904   } else {
 905     // thread is doing an Object.wait() call
 906     obj = mon->object();
 907     assert(obj != NULL, "Object.wait() should have an object");
 908   }
 909 
 910   if (obj == NULL) {
 911     *monitor_ptr = NULL;
 912   } else {
 913     HandleMark hm(current_thread);
 914     Handle     hobj(current_thread, obj);
 915     *monitor_ptr = jni_reference(calling_thread, hobj);
 916   }
 917   return JVMTI_ERROR_NONE;
 918 }
 919 
 920 jvmtiError
 921 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
 922                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 923   // Note:
 924   // calling_thread is the thread that requested the list of monitors for java_thread.
 925   // java_thread is the thread owning the monitors.
 926   // current_thread is the thread executing this code, can be a non-JavaThread (e.g. VM Thread).
 927   // And they all may be different threads.
 928   jvmtiError err = JVMTI_ERROR_NONE;
 929   Thread *current_thread = Thread::current();
 930   assert(java_thread->is_handshake_safe_for(current_thread),
 931          "call by myself or at handshake");
 932 
 933   if (JvmtiEnvBase::is_cthread_with_continuation(java_thread)) {
 934     // Carrier thread with a mounted continuation case.
 935     // No contended monitor can be owned by carrier thread in this case.
 936     return JVMTI_ERROR_NONE;
 937   }
 938   if (java_thread->has_last_Java_frame()) {
 939     ResourceMark rm(current_thread);
 940     HandleMark   hm(current_thread);
 941     RegisterMap  reg_map(java_thread,
 942                          RegisterMap::UpdateMap::include,
 943                          RegisterMap::ProcessFrames::include,
 944                          RegisterMap::WalkContinuation::skip);
 945 
 946     int depth = 0;
 947     for (javaVFrame *jvf = get_cthread_last_java_vframe(java_thread, &reg_map);
 948          jvf != NULL; jvf = jvf->java_sender()) {
 949       if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 950         // add locked objects for this frame into list
 951         err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 952         if (err != JVMTI_ERROR_NONE) {
 953           return err;
 954         }
 955       }
 956     }
 957   }
 958 
 959   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 960   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 961   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 962   err = jmc.error();
 963 
 964   return err;
 965 }
 966 
 967 jvmtiError
 968 JvmtiEnvBase::get_owned_monitors(JavaThread* calling_thread, JavaThread* java_thread, javaVFrame* jvf,
 969                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 970   jvmtiError err = JVMTI_ERROR_NONE;
 971   Thread *current_thread = Thread::current();
 972   assert(java_thread->is_handshake_safe_for(current_thread),
 973          "call by myself or at handshake");
 974 
 975   int depth = 0;
 976   for ( ; jvf != NULL; jvf = jvf->java_sender()) {
 977     if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 978       // Add locked objects for this frame into list.
 979       err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth - 1);
 980       if (err != JVMTI_ERROR_NONE) {
 981         return err;
 982       }
 983     }
 984   }
 985 
 986   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 987   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 988   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 989   err = jmc.error();
 990 
 991   return err;
 992 }
 993 
 994 // Save JNI local handles for any objects that this frame owns.
 995 jvmtiError
 996 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
 997                                  javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, jint stack_depth) {
 998   jvmtiError err = JVMTI_ERROR_NONE;
 999   Thread* current_thread = Thread::current();
1000   ResourceMark rm(current_thread);
1001   HandleMark   hm(current_thread);
1002 
1003   GrowableArray<MonitorInfo*>* mons = jvf->monitors();
1004   if (mons->is_empty()) {
1005     return err;  // this javaVFrame holds no monitors
1006   }
1007 
1008   oop wait_obj = NULL;
1009   {
1010     // The ObjectMonitor* can't be async deflated since we are either
1011     // at a safepoint or the calling thread is operating on itself so
1012     // it cannot leave the underlying wait() call.
1013     // Save object of current wait() call (if any) for later comparison.
1014     ObjectMonitor *mon = java_thread->current_waiting_monitor();
1015     if (mon != NULL) {
1016       wait_obj = mon->object();
1017     }
1018   }
1019   oop pending_obj = NULL;
1020   {
1021     // The ObjectMonitor* can't be async deflated since we are either
1022     // at a safepoint or the calling thread is operating on itself so
1023     // it cannot leave the underlying enter() call.
1024     // Save object of current enter() call (if any) for later comparison.
1025     ObjectMonitor *mon = java_thread->current_pending_monitor();
1026     if (mon != NULL) {
1027       pending_obj = mon->object();
1028     }
1029   }
1030 
1031   for (int i = 0; i < mons->length(); i++) {
1032     MonitorInfo *mi = mons->at(i);
1033 
1034     if (mi->owner_is_scalar_replaced()) continue;
1035 
1036     oop obj = mi->owner();
1037     if (obj == NULL) {
1038       // this monitor doesn't have an owning object so skip it
1039       continue;
1040     }
1041 
1042     if (wait_obj == obj) {
1043       // the thread is waiting on this monitor so it isn't really owned
1044       continue;
1045     }
1046 
1047     if (pending_obj == obj) {
1048       // the thread is pending on this monitor so it isn't really owned
1049       continue;
1050     }
1051 
1052     if (owned_monitors_list->length() > 0) {
1053       // Our list has at least one object on it so we have to check
1054       // for recursive object locking
1055       bool found = false;
1056       for (int j = 0; j < owned_monitors_list->length(); j++) {
1057         jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
1058         oop check = JNIHandles::resolve(jobj);
1059         if (check == obj) {
1060           found = true;  // we found the object
1061           break;
1062         }
1063       }
1064 
1065       if (found) {
1066         // already have this object so don't include it
1067         continue;
1068       }
1069     }
1070 
1071     // add the owning object to our list
1072     jvmtiMonitorStackDepthInfo *jmsdi;
1073     err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1074     if (err != JVMTI_ERROR_NONE) {
1075         return err;
1076     }
1077     Handle hobj(Thread::current(), obj);
1078     jmsdi->monitor = jni_reference(calling_thread, hobj);
1079     jmsdi->stack_depth = stack_depth;
1080     owned_monitors_list->append(jmsdi);
1081   }
1082 
1083   return err;
1084 }
1085 
1086 jvmtiError
1087 JvmtiEnvBase::get_stack_trace(javaVFrame *jvf,
1088                               jint start_depth, jint max_count,
1089                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1090   Thread *current_thread = Thread::current();
1091   ResourceMark rm(current_thread);
1092   HandleMark hm(current_thread);
1093   int count = 0;
1094 
1095   if (start_depth != 0) {
1096     if (start_depth > 0) {
1097       for (int j = 0; j < start_depth && jvf != NULL; j++) {
1098         jvf = jvf->java_sender();
1099       }
1100       if (jvf == NULL) {
1101         // start_depth is deeper than the stack depth.
1102         return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1103       }
1104     } else { // start_depth < 0
1105       // We are referencing the starting depth based on the oldest
1106       // part of the stack.
1107       // Optimize to limit the number of times that java_sender() is called.
1108       javaVFrame *jvf_cursor = jvf;
1109       javaVFrame *jvf_prev = NULL;
1110       javaVFrame *jvf_prev_prev = NULL;
1111       int j = 0;
1112       while (jvf_cursor != NULL) {
1113         jvf_prev_prev = jvf_prev;
1114         jvf_prev = jvf_cursor;
1115         for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
1116           jvf_cursor = jvf_cursor->java_sender();
1117         }
1118       }
1119       if (j == start_depth) {
1120         // Previous pointer is exactly where we want to start.
1121         jvf = jvf_prev;
1122       } else {
1123         // We need to back up further to get to the right place.
1124         if (jvf_prev_prev == NULL) {
1125           // The -start_depth is greater than the stack depth.
1126           return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1127         }
1128         // j is now the number of frames on the stack starting with
1129         // jvf_prev, we start from jvf_prev_prev and move older on
1130         // the stack that many, and the result is -start_depth frames
1131         // remaining.
1132         jvf = jvf_prev_prev;
1133         for (; j < 0; j++) {
1134           jvf = jvf->java_sender();
1135         }
1136       }
1137     }
1138   }
1139   for (; count < max_count && jvf != NULL; count++) {
1140     frame_buffer[count].method = jvf->method()->jmethod_id();
1141     frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
1142     jvf = jvf->java_sender();
1143   }
1144   *count_ptr = count;
1145   return JVMTI_ERROR_NONE;
1146 }
1147 
1148 jvmtiError
1149 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
1150                               jint start_depth, jint max_count,
1151                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1152   Thread *current_thread = Thread::current();
1153   assert(SafepointSynchronize::is_at_safepoint() ||
1154          java_thread->is_handshake_safe_for(current_thread),
1155          "call by myself / at safepoint / at handshake");
1156   int count = 0;
1157   jvmtiError err = JVMTI_ERROR_NONE;
1158 
1159   if (java_thread->has_last_Java_frame()) {
1160     RegisterMap reg_map(java_thread,
1161                         RegisterMap::UpdateMap::include,
1162                         RegisterMap::ProcessFrames::skip,
1163                         RegisterMap::WalkContinuation::skip);
1164     ResourceMark rm(current_thread);
1165     javaVFrame *jvf = get_cthread_last_java_vframe(java_thread, &reg_map);
1166 
1167     err = get_stack_trace(jvf, start_depth, max_count, frame_buffer, count_ptr);
1168   } else {
1169     *count_ptr = 0;
1170     if (start_depth != 0) {
1171       // no frames and there is a starting depth
1172       err = JVMTI_ERROR_ILLEGAL_ARGUMENT;
1173     }
1174   }
1175   return err;
1176 }
1177 
1178 jint
1179 JvmtiEnvBase::get_frame_count(javaVFrame *jvf) {
1180   int count = 0;
1181 
1182   while (jvf != NULL) {
1183     jvf = jvf->java_sender();
1184     count++;
1185   }
1186   return count;
1187 }
1188 
1189 jvmtiError
1190 JvmtiEnvBase::get_frame_count(JavaThread* jt, jint *count_ptr) {
1191   Thread *current_thread = Thread::current();
1192   assert(current_thread == jt ||
1193          SafepointSynchronize::is_at_safepoint() ||
1194          jt->is_handshake_safe_for(current_thread),
1195          "call by myself / at safepoint / at handshake");
1196 
1197   if (!jt->has_last_Java_frame()) { // no Java frames
1198     *count_ptr = 0;
1199   } else {
1200     ResourceMark rm(current_thread);
1201     RegisterMap reg_map(jt,
1202                         RegisterMap::UpdateMap::include,
1203                         RegisterMap::ProcessFrames::include,
1204                         RegisterMap::WalkContinuation::skip);
1205     javaVFrame *jvf = get_cthread_last_java_vframe(jt, &reg_map);
1206 
1207     *count_ptr = get_frame_count(jvf);
1208   }
1209   return JVMTI_ERROR_NONE;
1210 }
1211 
1212 jvmtiError
1213 JvmtiEnvBase::get_frame_count(oop vthread_oop, jint *count_ptr) {
1214   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1215     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1216   }
1217   Thread *current_thread = Thread::current();
1218   ResourceMark rm(current_thread);
1219   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1220 
1221   *count_ptr = get_frame_count(jvf);
1222   return JVMTI_ERROR_NONE;
1223 }
1224 
1225 jvmtiError
1226 JvmtiEnvBase::get_frame_location(javaVFrame* jvf, jint depth,
1227                                  jmethodID* method_ptr, jlocation* location_ptr) {
1228   int cur_depth = 0;
1229 
1230   while (jvf != NULL && cur_depth < depth) {
1231     jvf = jvf->java_sender();
1232     cur_depth++;
1233   }
1234   assert(depth >= cur_depth, "ran out of frames too soon");
1235   if (jvf == NULL) {
1236     return JVMTI_ERROR_NO_MORE_FRAMES;
1237   }
1238   Method* method = jvf->method();
1239   if (method->is_native()) {
1240     *location_ptr = -1;
1241   } else {
1242     *location_ptr = jvf->bci();
1243   }
1244   *method_ptr = method->jmethod_id();
1245   return JVMTI_ERROR_NONE;
1246 }
1247 
1248 jvmtiError
1249 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
1250                                  jmethodID* method_ptr, jlocation* location_ptr) {
1251   Thread* current = Thread::current();
1252   assert(java_thread->is_handshake_safe_for(current),
1253          "call by myself or at handshake");
1254   if (!java_thread->has_last_Java_frame()) {
1255     return JVMTI_ERROR_NO_MORE_FRAMES;
1256   }
1257   ResourceMark rm(current);
1258   HandleMark hm(current);
1259   RegisterMap reg_map(java_thread,
1260                       RegisterMap::UpdateMap::include,
1261                       RegisterMap::ProcessFrames::skip,
1262                       RegisterMap::WalkContinuation::include);
1263   javaVFrame* jvf = JvmtiEnvBase::get_cthread_last_java_vframe(java_thread, &reg_map);
1264 
1265   return get_frame_location(jvf, depth, method_ptr, location_ptr);
1266 }
1267 
1268 jvmtiError
1269 JvmtiEnvBase::get_frame_location(oop vthread_oop, jint depth,
1270                                  jmethodID* method_ptr, jlocation* location_ptr) {
1271   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1272     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1273   }
1274   Thread* current = Thread::current();
1275   ResourceMark rm(current);
1276   HandleMark hm(current);
1277   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1278 
1279   return get_frame_location(jvf, depth, method_ptr, location_ptr);
1280 }
1281 
1282 jvmtiError
1283 JvmtiEnvBase::set_frame_pop(JvmtiThreadState* state, javaVFrame* jvf, jint depth) {
1284   for (int d = 0; jvf != NULL && d < depth; d++) {
1285     jvf = jvf->java_sender();
1286   }
1287   if (jvf == NULL) {
1288     return JVMTI_ERROR_NO_MORE_FRAMES;
1289   }
1290   if (jvf->method()->is_native()) {
1291     return JVMTI_ERROR_OPAQUE_FRAME;
1292   }
1293   assert(jvf->frame_pointer() != NULL, "frame pointer mustn't be NULL");
1294   int frame_number = (int)get_frame_count(jvf);
1295   state->env_thread_state((JvmtiEnvBase*)this)->set_frame_pop(frame_number);
1296   return JVMTI_ERROR_NONE;
1297 }
1298 
1299 bool
1300 JvmtiEnvBase::is_cthread_with_mounted_vthread(JavaThread* jt) {
1301   oop thread_oop = jt->threadObj();
1302   assert(thread_oop != NULL, "sanity check");
1303   oop mounted_vt = jt->jvmti_vthread();
1304 
1305   return mounted_vt != NULL && mounted_vt != thread_oop;
1306 }
1307 
1308 bool
1309 JvmtiEnvBase::is_cthread_with_continuation(JavaThread* jt) {
1310   const ContinuationEntry* cont_entry = NULL;
1311   if (jt->has_last_Java_frame()) {
1312     cont_entry = jt->vthread_continuation();
1313   }
1314   return cont_entry != NULL && is_cthread_with_mounted_vthread(jt);
1315 }
1316 
1317 // If (thread == NULL) then return current thread object.
1318 // Otherwise return JNIHandles::resolve_external_guard(thread).
1319 oop
1320 JvmtiEnvBase::current_thread_obj_or_resolve_external_guard(jthread thread) {
1321   oop thread_obj = JNIHandles::resolve_external_guard(thread);
1322   if (thread == NULL) {
1323     thread_obj = get_vthread_or_thread_oop(JavaThread::current());
1324   }
1325   return thread_obj;
1326 }
1327 
1328 jvmtiError
1329 JvmtiEnvBase::get_threadOop_and_JavaThread(ThreadsList* t_list, jthread thread,
1330                                            JavaThread** jt_pp, oop* thread_oop_p) {
1331   JavaThread* cur_thread = JavaThread::current();
1332   JavaThread* java_thread = NULL;
1333   oop thread_oop = NULL;
1334 
1335   if (thread == NULL) {
1336     java_thread = cur_thread;
1337     thread_oop = get_vthread_or_thread_oop(java_thread);
1338     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::Thread_klass())) {
1339       return JVMTI_ERROR_INVALID_THREAD;
1340     }
1341   } else {
1342     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(t_list, thread, &java_thread, &thread_oop);
1343     if (err != JVMTI_ERROR_NONE) {
1344       // We got an error code so we don't have a JavaThread*, but only return
1345       // an error from here if we didn't get a valid thread_oop. In a vthread case
1346       // the cv_external_thread_to_JavaThread is expected to correctly set the
1347       // thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1348       if (thread_oop == NULL || err != JVMTI_ERROR_INVALID_THREAD) {
1349         *thread_oop_p = thread_oop;
1350         return err;
1351       }
1352     }
1353     if (java_thread == NULL && java_lang_VirtualThread::is_instance(thread_oop)) {
1354       java_thread = get_JavaThread_or_null(thread_oop);
1355     }
1356   }
1357   *jt_pp = java_thread;
1358   *thread_oop_p = thread_oop;
1359   if (java_lang_VirtualThread::is_instance(thread_oop) &&
1360       !JvmtiEnvBase::is_vthread_alive(thread_oop)) {
1361     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1362   }
1363   return JVMTI_ERROR_NONE;
1364 }
1365 
1366 jvmtiError
1367 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
1368   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1369   Thread* current_thread = VMThread::vm_thread();
1370   assert(current_thread == Thread::current(), "must be");
1371 
1372   HandleMark hm(current_thread);
1373   Handle hobj;
1374 
1375   // Check arguments
1376   {
1377     oop mirror = JNIHandles::resolve_external_guard(object);
1378     NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
1379     NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
1380 
1381     hobj = Handle(current_thread, mirror);
1382   }
1383 
1384   ThreadsListHandle tlh(current_thread);
1385   JavaThread *owning_thread = NULL;
1386   ObjectMonitor* mon = NULL;
1387   jvmtiMonitorUsage ret = {
1388       NULL, 0, 0, NULL, 0, NULL
1389   };
1390 
1391   uint32_t debug_bits = 0;
1392   // first derive the object's owner and entry_count (if any)
1393   owning_thread = Threads::owning_thread_from_object(tlh.list(), hobj(), &mon);
1394   if (owning_thread != NULL) {
1395     Handle th(current_thread, get_vthread_or_thread_oop(owning_thread));
1396     ret.owner = (jthread)jni_reference(calling_thread, th);
1397     // The recursions field of a monitor does not reflect recursions
1398     // as lightweight locks before inflating the monitor are not included.
1399     // We have to count the number of recursive monitor entries the hard way.
1400     // We pass a handle to survive any GCs along the way.
1401     ret.entry_count = count_locked_objects(owning_thread, hobj);
1402   }
1403   // implied else: entry_count == 0
1404 
1405   jint nWant = 0, nWait = 0;
1406   if (mon != NULL) {
1407     // this object has a heavyweight monitor
1408     nWant = mon->contentions(); // # of threads contending for monitor
1409     nWait = mon->waiters();     // # of threads in Object.wait()
1410     ret.waiter_count = nWant + nWait;
1411     ret.notify_waiter_count = nWait;
1412   } else {
1413     // this object has a lightweight monitor
1414     ret.waiter_count = 0;
1415     ret.notify_waiter_count = 0;
1416   }
1417 
1418   // Allocate memory for heavyweight and lightweight monitor.
1419   jvmtiError err;
1420   err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
1421   if (err != JVMTI_ERROR_NONE) {
1422     return err;
1423   }
1424   err = allocate(ret.notify_waiter_count * sizeof(jthread *),
1425                  (unsigned char**)&ret.notify_waiters);
1426   if (err != JVMTI_ERROR_NONE) {
1427     deallocate((unsigned char*)ret.waiters);
1428     return err;
1429   }
1430 
1431   // now derive the rest of the fields
1432   if (mon != NULL) {
1433     // this object has a heavyweight monitor
1434 
1435     // Number of waiters may actually be less than the waiter count.
1436     // So NULL out memory so that unused memory will be NULL.
1437     memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1438     memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1439 
1440     if (ret.waiter_count > 0) {
1441       // we have contending and/or waiting threads
1442       if (nWant > 0) {
1443         // we have contending threads
1444         ResourceMark rm(current_thread);
1445         // get_pending_threads returns only java thread so we do not need to
1446         // check for non java threads.
1447         GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(tlh.list(), nWant, (address)mon);
1448         if (wantList->length() < nWant) {
1449           // robustness: the pending list has gotten smaller
1450           nWant = wantList->length();
1451         }
1452         for (int i = 0; i < nWant; i++) {
1453           JavaThread *pending_thread = wantList->at(i);
1454           Handle th(current_thread, get_vthread_or_thread_oop(pending_thread));
1455           ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1456         }
1457       }
1458       if (nWait > 0) {
1459         // we have threads in Object.wait()
1460         int offset = nWant;  // add after any contending threads
1461         ObjectWaiter *waiter = mon->first_waiter();
1462         for (int i = 0, j = 0; i < nWait; i++) {
1463           if (waiter == NULL) {
1464             // robustness: the waiting list has gotten smaller
1465             nWait = j;
1466             break;
1467           }
1468           JavaThread *w = mon->thread_of_waiter(waiter);
1469           if (w != NULL) {
1470             // If the thread was found on the ObjectWaiter list, then
1471             // it has not been notified. This thread can't change the
1472             // state of the monitor so it doesn't need to be suspended.
1473             Handle th(current_thread, get_vthread_or_thread_oop(w));
1474             ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1475             ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1476           }
1477           waiter = mon->next_waiter(waiter);
1478         }
1479       }
1480     } // ThreadsListHandle is destroyed here.
1481 
1482     // Adjust count. nWant and nWait count values may be less than original.
1483     ret.waiter_count = nWant + nWait;
1484     ret.notify_waiter_count = nWait;
1485   } else {
1486     // this object has a lightweight monitor and we have nothing more
1487     // to do here because the defaults are just fine.
1488   }
1489 
1490   // we don't update return parameter unless everything worked
1491   *info_ptr = ret;
1492 
1493   return JVMTI_ERROR_NONE;
1494 }
1495 
1496 jvmtiError
1497 JvmtiEnvBase::check_thread_list(jint count, const jthread* list) {
1498   if (list == NULL && count != 0) {
1499     return JVMTI_ERROR_NULL_POINTER;
1500   }
1501   for (int i = 0; i < count; i++) {
1502     jthread thread = list[i];
1503     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1504     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::VirtualThread_klass())) {
1505       return JVMTI_ERROR_INVALID_THREAD;
1506     }
1507   }
1508   return JVMTI_ERROR_NONE;
1509 }
1510 
1511 bool
1512 JvmtiEnvBase::is_in_thread_list(jint count, const jthread* list, oop jt_oop) {
1513   for (int idx = 0; idx < count; idx++) {
1514     jthread thread = list[idx];
1515     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1516     if (thread_oop == jt_oop) {
1517       return true;
1518     }
1519   }
1520   return false;
1521 }
1522 
1523 // java_thread - protected by ThreadsListHandle
1524 jvmtiError
1525 JvmtiEnvBase::suspend_thread(oop thread_oop, JavaThread* java_thread, bool single_suspend,
1526                              int* need_safepoint_p) {
1527   JavaThread* current = JavaThread::current();
1528   HandleMark hm(current);
1529   Handle thread_h(current, thread_oop);
1530   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1531 
1532   if (is_virtual) {
1533     if (single_suspend) {
1534       if (JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1535         return JVMTI_ERROR_THREAD_SUSPENDED;
1536       }
1537       JvmtiVTSuspender::register_vthread_suspend(thread_h());
1538       // Check if virtual thread is mounted and there is a java_thread.
1539       // A non-NULL java_thread is always passed in the !single_suspend case.
1540       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1541       java_thread = carrier_thread == NULL ? NULL : java_lang_Thread::thread(carrier_thread);
1542     }
1543     // The java_thread can be still blocked in VTMS transition after a previous JVMTI resume call.
1544     // There is no need to suspend the java_thread in this case. After vthread unblocking,
1545     // it will check for ext_suspend request and suspend itself if necessary.
1546     if (java_thread == NULL || java_thread->is_suspended()) {
1547       // We are done if the virtual thread is unmounted or
1548       // the java_thread is externally suspended.
1549       return JVMTI_ERROR_NONE;
1550     }
1551     // The virtual thread is mounted: suspend the java_thread.
1552   }
1553   // Don't allow hidden thread suspend request.
1554   if (java_thread->is_hidden_from_external_view()) {
1555     return JVMTI_ERROR_NONE;
1556   }
1557   bool is_passive_cthread = is_passive_carrier_thread(java_thread, thread_h());
1558 
1559   // A case of non-virtual thread.
1560   if (!is_virtual) {
1561     // Thread.suspend() is used in some tests. It sets jt->is_suspended() only.
1562     if (java_thread->is_carrier_thread_suspended() ||
1563         (!is_passive_cthread && java_thread->is_suspended())) {
1564       return JVMTI_ERROR_THREAD_SUSPENDED;
1565     }
1566     java_thread->set_carrier_thread_suspended();
1567   }
1568   assert(!java_thread->is_in_VTMS_transition(), "sanity check");
1569 
1570   assert(!single_suspend || (!is_virtual && java_thread->is_carrier_thread_suspended()) ||
1571           (is_virtual && JvmtiVTSuspender::is_vthread_suspended(thread_h())),
1572          "sanity check");
1573 
1574   // An attempt to handshake-suspend a passive carrier thread will result in
1575   // suspension of mounted virtual thread. So, we just mark it as suspended
1576   // and it will be actually suspended at virtual thread unmount transition.
1577   if (!is_passive_cthread) {
1578     assert(single_suspend || is_virtual, "SuspendAllVirtualThreads should never suspend non-virtual threads");
1579     // Case of mounted virtual or attached carrier thread.
1580     if (!JvmtiSuspendControl::suspend(java_thread)) {
1581       // Thread is already suspended or in process of exiting.
1582       if (java_thread->is_exiting()) {
1583         // The thread was in the process of exiting.
1584         return JVMTI_ERROR_THREAD_NOT_ALIVE;
1585       }
1586       return JVMTI_ERROR_THREAD_SUSPENDED;
1587     }
1588   }
1589   return JVMTI_ERROR_NONE;
1590 }
1591 
1592 // java_thread - protected by ThreadsListHandle
1593 jvmtiError
1594 JvmtiEnvBase::resume_thread(oop thread_oop, JavaThread* java_thread, bool single_resume) {
1595   JavaThread* current = JavaThread::current();
1596   HandleMark hm(current);
1597   Handle thread_h(current, thread_oop);
1598   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1599 
1600   if (is_virtual) {
1601     if (single_resume) {
1602       if (!JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1603         return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1604       }
1605       JvmtiVTSuspender::register_vthread_resume(thread_h());
1606       // Check if virtual thread is mounted and there is a java_thread.
1607       // A non-NULL java_thread is always passed in the !single_resume case.
1608       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1609       java_thread = carrier_thread == NULL ? NULL : java_lang_Thread::thread(carrier_thread);
1610     }
1611     // The java_thread can be still blocked in VTMS transition after a previous JVMTI suspend call.
1612     // There is no need to resume the java_thread in this case. After vthread unblocking,
1613     // it will check for is_vthread_suspended request and remain resumed if necessary.
1614     if (java_thread == NULL || !java_thread->is_suspended()) {
1615       // We are done if the virtual thread is unmounted or
1616       // the java_thread is not externally suspended.
1617       return JVMTI_ERROR_NONE;
1618     }
1619     // The virtual thread is mounted and java_thread is supended: resume the java_thread.
1620   }
1621   // Don't allow hidden thread resume request.
1622   if (java_thread->is_hidden_from_external_view()) {
1623     return JVMTI_ERROR_NONE;
1624   }
1625   bool is_passive_cthread = is_passive_carrier_thread(java_thread, thread_h());
1626 
1627   // A case of a non-virtual thread.
1628   if (!is_virtual) {
1629     if (!java_thread->is_carrier_thread_suspended() &&
1630         (is_passive_cthread || !java_thread->is_suspended())) {
1631       return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1632     }
1633     java_thread->clear_carrier_thread_suspended();
1634   }
1635   assert(!java_thread->is_in_VTMS_transition(), "sanity check");
1636 
1637   if (!is_passive_cthread) {
1638     assert(single_resume || is_virtual, "ResumeAllVirtualThreads should never resume non-virtual threads");
1639     if (java_thread->is_suspended()) {
1640       if (!JvmtiSuspendControl::resume(java_thread)) {
1641         return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1642       }
1643     }
1644   }
1645   return JVMTI_ERROR_NONE;
1646 }
1647 
1648 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1649   _env = env;
1650   _allocations = new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<unsigned char*>(20, mtServiceability);
1651   _failed = false;
1652 }
1653 ResourceTracker::~ResourceTracker() {
1654   if (_failed) {
1655     for (int i=0; i<_allocations->length(); i++) {
1656       _env->deallocate(_allocations->at(i));
1657     }
1658   }
1659   delete _allocations;
1660 }
1661 
1662 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1663   unsigned char *ptr;
1664   jvmtiError err = _env->allocate(size, &ptr);
1665   if (err == JVMTI_ERROR_NONE) {
1666     _allocations->append(ptr);
1667     *mem_ptr = ptr;
1668   } else {
1669     *mem_ptr = NULL;
1670     _failed = true;
1671   }
1672   return err;
1673  }
1674 
1675 unsigned char* ResourceTracker::allocate(jlong size) {
1676   unsigned char* ptr;
1677   allocate(size, &ptr);
1678   return ptr;
1679 }
1680 
1681 char* ResourceTracker::strdup(const char* str) {
1682   char *dup_str = (char*)allocate(strlen(str)+1);
1683   if (dup_str != NULL) {
1684     strcpy(dup_str, str);
1685   }
1686   return dup_str;
1687 }
1688 
1689 struct StackInfoNode {
1690   struct StackInfoNode *next;
1691   jvmtiStackInfo info;
1692 };
1693 
1694 // Create a jvmtiStackInfo inside a linked list node and create a
1695 // buffer for the frame information, both allocated as resource objects.
1696 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1697 // Note that either or both of thr and thread_oop
1698 // may be null if the thread is new or has exited.
1699 void
1700 MultipleStackTracesCollector::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1701 #ifdef ASSERT
1702   Thread *current_thread = Thread::current();
1703   assert(SafepointSynchronize::is_at_safepoint() ||
1704          thr == NULL ||
1705          thr->is_handshake_safe_for(current_thread),
1706          "unmounted virtual thread / call by myself / at safepoint / at handshake");
1707 #endif
1708 
1709   jint state = 0;
1710   struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
1711   jvmtiStackInfo *infop = &(node->info);
1712 
1713   node->next = head();
1714   set_head(node);
1715   infop->frame_count = 0;
1716   infop->frame_buffer = NULL;
1717   infop->thread = jt;
1718 
1719   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1720     state = JvmtiEnvBase::get_vthread_state(thread_oop, thr);
1721 
1722     if ((state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1723       javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(thread_oop);
1724       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1725       _result = env()->get_stack_trace(jvf, 0, max_frame_count(),
1726                                        infop->frame_buffer, &(infop->frame_count));
1727     }
1728   } else {
1729     state = JvmtiEnvBase::get_thread_state(thread_oop, thr);
1730     if (thr != NULL && (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1731       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1732       _result = env()->get_stack_trace(thr, 0, max_frame_count(),
1733                                        infop->frame_buffer, &(infop->frame_count));
1734     }
1735   }
1736   _frame_count_total += infop->frame_count;
1737   infop->state = state;
1738 }
1739 
1740 // Based on the stack information in the linked list, allocate memory
1741 // block to return and fill it from the info in the linked list.
1742 void
1743 MultipleStackTracesCollector::allocate_and_fill_stacks(jint thread_count) {
1744   // do I need to worry about alignment issues?
1745   jlong alloc_size =  thread_count       * sizeof(jvmtiStackInfo)
1746                     + _frame_count_total * sizeof(jvmtiFrameInfo);
1747   env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1748 
1749   // pointers to move through the newly allocated space as it is filled in
1750   jvmtiStackInfo *si = _stack_info + thread_count;      // bottom of stack info
1751   jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si;            // is the top of frame info
1752 
1753   // copy information in resource area into allocated buffer
1754   // insert stack info backwards since linked list is backwards
1755   // insert frame info forwards
1756   // walk the StackInfoNodes
1757   for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {
1758     jint frame_count = sin->info.frame_count;
1759     size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
1760     --si;
1761     memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
1762     if (frames_size == 0) {
1763       si->frame_buffer = NULL;
1764     } else {
1765       memcpy(fi, sin->info.frame_buffer, frames_size);
1766       si->frame_buffer = fi;  // point to the new allocated copy of the frames
1767       fi += frame_count;
1768     }
1769   }
1770   assert(si == _stack_info, "the last copied stack info must be the first record");
1771   assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1772          "the last copied frame info must be the last record");
1773 }
1774 
1775 
1776 void
1777 VM_GetThreadListStackTraces::doit() {
1778   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1779 
1780   ResourceMark rm;
1781   ThreadsListHandle tlh;
1782   for (int i = 0; i < _thread_count; ++i) {
1783     jthread jt = _thread_list[i];
1784     JavaThread* java_thread = NULL;
1785     oop thread_oop = NULL;
1786     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), jt, &java_thread, &thread_oop);
1787     if (err != JVMTI_ERROR_NONE) {
1788       // We got an error code so we don't have a JavaThread *, but
1789       // only return an error from here if we didn't get a valid
1790       // thread_oop.
1791       // In the virtual thread case the cv_external_thread_to_JavaThread is expected to correctly set
1792       // the thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1793       if (thread_oop == NULL) {
1794         _collector.set_result(err);
1795         return;
1796       }
1797       // We have a valid thread_oop.
1798     }
1799     _collector.fill_frames(jt, java_thread, thread_oop);
1800   }
1801   _collector.allocate_and_fill_stacks(_thread_count);
1802 }
1803 
1804 void
1805 GetSingleStackTraceClosure::do_thread(Thread *target) {
1806   JavaThread *jt = JavaThread::cast(target);
1807   oop thread_oop = jt->threadObj();
1808 
1809   if (!jt->is_exiting() && thread_oop != NULL) {
1810     ResourceMark rm;
1811     _collector.fill_frames(_jthread, jt, thread_oop);
1812     _collector.allocate_and_fill_stacks(1);
1813   }
1814 }
1815 
1816 void
1817 VM_GetAllStackTraces::doit() {
1818   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1819 
1820   ResourceMark rm;
1821   _final_thread_count = 0;
1822   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1823     oop thread_oop = jt->threadObj();
1824     if (thread_oop != NULL &&
1825         !jt->is_exiting() &&
1826         java_lang_Thread::is_alive(thread_oop) &&
1827         !jt->is_hidden_from_external_view()) {
1828       ++_final_thread_count;
1829       // Handle block of the calling thread is used to create local refs.
1830       _collector.fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
1831                              jt, thread_oop);
1832     }
1833   }
1834   _collector.allocate_and_fill_stacks(_final_thread_count);
1835 }
1836 
1837 // Verifies that the top frame is a java frame in an expected state.
1838 // Deoptimizes frame if needed.
1839 // Checks that the frame method signature matches the return type (tos).
1840 // HandleMark must be defined in the caller only.
1841 // It is to keep a ret_ob_h handle alive after return to the caller.
1842 jvmtiError
1843 JvmtiEnvBase::check_top_frame(Thread* current_thread, JavaThread* java_thread,
1844                               jvalue value, TosState tos, Handle* ret_ob_h) {
1845   ResourceMark rm(current_thread);
1846 
1847   javaVFrame* jvf = jvf_for_thread_and_depth(java_thread, 0);
1848   NULL_CHECK(jvf, JVMTI_ERROR_NO_MORE_FRAMES);
1849 
1850   if (jvf->method()->is_native()) {
1851     return JVMTI_ERROR_OPAQUE_FRAME;
1852   }
1853 
1854   // If the frame is a compiled one, need to deoptimize it.
1855   if (jvf->is_compiled_frame()) {
1856     if (!jvf->fr().can_be_deoptimized()) {
1857       return JVMTI_ERROR_OPAQUE_FRAME;
1858     }
1859     Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());
1860   }
1861 
1862   // Get information about method return type
1863   Symbol* signature = jvf->method()->signature();
1864 
1865   ResultTypeFinder rtf(signature);
1866   TosState fr_tos = as_TosState(rtf.type());
1867   if (fr_tos != tos) {
1868     if (tos != itos || (fr_tos != btos && fr_tos != ztos && fr_tos != ctos && fr_tos != stos)) {
1869       return JVMTI_ERROR_TYPE_MISMATCH;
1870     }
1871   }
1872 
1873   // Check that the jobject class matches the return type signature.
1874   jobject jobj = value.l;
1875   if (tos == atos && jobj != NULL) { // NULL reference is allowed
1876     Handle ob_h(current_thread, JNIHandles::resolve_external_guard(jobj));
1877     NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
1878     Klass* ob_k = ob_h()->klass();
1879     NULL_CHECK(ob_k, JVMTI_ERROR_INVALID_OBJECT);
1880 
1881     // Method return type signature.
1882     char* ty_sign = 1 + strchr(signature->as_C_string(), JVM_SIGNATURE_ENDFUNC);
1883 
1884     if (!VM_GetOrSetLocal::is_assignable(ty_sign, ob_k, current_thread)) {
1885       return JVMTI_ERROR_TYPE_MISMATCH;
1886     }
1887     *ret_ob_h = ob_h;
1888   }
1889   return JVMTI_ERROR_NONE;
1890 } /* end check_top_frame */
1891 
1892 
1893 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
1894 // Main difference is on the last stage in the interpreter.
1895 // The PopFrame stops method execution to continue execution
1896 // from the same method call instruction.
1897 // The ForceEarlyReturn forces return from method so the execution
1898 // continues at the bytecode following the method call.
1899 
1900 // thread - NOT protected by ThreadsListHandle and NOT pre-checked
1901 
1902 jvmtiError
1903 JvmtiEnvBase::force_early_return(jthread thread, jvalue value, TosState tos) {
1904   JavaThread* current_thread = JavaThread::current();
1905   HandleMark hm(current_thread);
1906 
1907   JvmtiVTMSTransitionDisabler disabler;
1908   ThreadsListHandle tlh(current_thread);
1909 
1910   JavaThread* java_thread = NULL;
1911   oop thread_obj = NULL;
1912   jvmtiError err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
1913 
1914   if (thread_obj != NULL && java_lang_VirtualThread::is_instance(thread_obj)) {
1915     // No support for virtual threads (yet).
1916     return JVMTI_ERROR_OPAQUE_FRAME;
1917   }
1918   if (err != JVMTI_ERROR_NONE) {
1919     return err;
1920   }
1921 
1922   // retrieve or create the state
1923   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1924   if (state == NULL) {
1925     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1926   }
1927 
1928   // Eagerly reallocate scalar replaced objects.
1929   EscapeBarrier eb(true, current_thread, java_thread);
1930   if (!eb.deoptimize_objects(0)) {
1931     // Reallocation of scalar replaced objects failed -> return with error
1932     return JVMTI_ERROR_OUT_OF_MEMORY;
1933   }
1934 
1935   SetForceEarlyReturn op(state, value, tos);
1936   if (java_thread == current_thread) {
1937     op.doit(java_thread, true /* self */);
1938   } else {
1939     Handshake::execute(&op, java_thread);
1940   }
1941   return op.result();
1942 }
1943 
1944 void
1945 SetForceEarlyReturn::doit(Thread *target, bool self) {
1946   JavaThread* java_thread = JavaThread::cast(target);
1947   Thread* current_thread = Thread::current();
1948   HandleMark   hm(current_thread);
1949 
1950   if (java_thread->is_exiting()) {
1951     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
1952   }
1953   if (!self) {
1954     if (!java_thread->is_suspended()) {
1955       _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1956       return;
1957     }
1958   }
1959 
1960   // Check to see if a ForceEarlyReturn was already in progress
1961   if (_state->is_earlyret_pending()) {
1962     // Probably possible for JVMTI clients to trigger this, but the
1963     // JPDA backend shouldn't allow this to happen
1964     _result = JVMTI_ERROR_INTERNAL;
1965     return;
1966   }
1967   {
1968     // The same as for PopFrame. Workaround bug:
1969     //  4812902: popFrame hangs if the method is waiting at a synchronize
1970     // Catch this condition and return an error to avoid hanging.
1971     // Now JVMTI spec allows an implementation to bail out with an opaque
1972     // frame error.
1973     OSThread* osThread = java_thread->osthread();
1974     if (osThread->get_state() == MONITOR_WAIT) {
1975       _result = JVMTI_ERROR_OPAQUE_FRAME;
1976       return;
1977     }
1978   }
1979 
1980   Handle ret_ob_h;
1981   _result = JvmtiEnvBase::check_top_frame(current_thread, java_thread, _value, _tos, &ret_ob_h);
1982   if (_result != JVMTI_ERROR_NONE) {
1983     return;
1984   }
1985   assert(_tos != atos || _value.l == NULL || ret_ob_h() != NULL,
1986          "return object oop must not be NULL if jobject is not NULL");
1987 
1988   // Update the thread state to reflect that the top frame must be
1989   // forced to return.
1990   // The current frame will be returned later when the suspended
1991   // thread is resumed and right before returning from VM to Java.
1992   // (see call_VM_base() in assembler_<cpu>.cpp).
1993 
1994   _state->set_earlyret_pending();
1995   _state->set_earlyret_oop(ret_ob_h());
1996   _state->set_earlyret_value(_value, _tos);
1997 
1998   // Set pending step flag for this early return.
1999   // It is cleared when next step event is posted.
2000   _state->set_pending_step_for_earlyret();
2001 }
2002 
2003 void
2004 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
2005   if ( _error != JVMTI_ERROR_NONE) {
2006     // Error occurred in previous iteration so no need to add
2007     // to the list.
2008     return;
2009   }
2010   // Filter out on stack monitors collected during stack walk.
2011   oop obj = mon->object();
2012   bool found = false;
2013   for (int j = 0; j < _owned_monitors_list->length(); j++) {
2014     jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
2015     oop check = JNIHandles::resolve(jobj);
2016     if (check == obj) {
2017       // On stack monitor already collected during the stack walk.
2018       found = true;
2019       break;
2020     }
2021   }
2022   if (found == false) {
2023     // This is off stack monitor (e.g. acquired via jni MonitorEnter).
2024     jvmtiError err;
2025     jvmtiMonitorStackDepthInfo *jmsdi;
2026     err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
2027     if (err != JVMTI_ERROR_NONE) {
2028       _error = err;
2029       return;
2030     }
2031     Handle hobj(Thread::current(), obj);
2032     jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
2033     // stack depth is unknown for this monitor.
2034     jmsdi->stack_depth = -1;
2035     _owned_monitors_list->append(jmsdi);
2036   }
2037 }
2038 
2039 GrowableArray<OopHandle>* JvmtiModuleClosure::_tbl = NULL;
2040 
2041 void JvmtiModuleClosure::do_module(ModuleEntry* entry) {
2042   assert_locked_or_safepoint(Module_lock);
2043   OopHandle module = entry->module_handle();
2044   guarantee(module.resolve() != NULL, "module object is NULL");
2045   _tbl->push(module);
2046 }
2047 
2048 jvmtiError
2049 JvmtiModuleClosure::get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr) {
2050   ResourceMark rm;
2051   MutexLocker mcld(ClassLoaderDataGraph_lock);
2052   MutexLocker ml(Module_lock);
2053 
2054   _tbl = new GrowableArray<OopHandle>(77);
2055   if (_tbl == NULL) {
2056     return JVMTI_ERROR_OUT_OF_MEMORY;
2057   }
2058 
2059   // Iterate over all the modules loaded to the system.
2060   ClassLoaderDataGraph::modules_do(&do_module);
2061 
2062   jint len = _tbl->length();
2063   guarantee(len > 0, "at least one module must be present");
2064 
2065   jobject* array = (jobject*)env->jvmtiMalloc((jlong)(len * sizeof(jobject)));
2066   if (array == NULL) {
2067     return JVMTI_ERROR_OUT_OF_MEMORY;
2068   }
2069   for (jint idx = 0; idx < len; idx++) {
2070     array[idx] = JNIHandles::make_local(_tbl->at(idx).resolve());
2071   }
2072   _tbl = NULL;
2073   *modules_ptr = array;
2074   *module_count_ptr = len;
2075   return JVMTI_ERROR_NONE;
2076 }
2077 
2078 void
2079 UpdateForPopTopFrameClosure::doit(Thread *target, bool self) {
2080   Thread* current_thread  = Thread::current();
2081   HandleMark hm(current_thread);
2082   JavaThread* java_thread = JavaThread::cast(target);
2083 
2084   if (java_thread->is_exiting()) {
2085     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2086   }
2087   assert(java_thread == _state->get_thread(), "Must be");
2088 
2089   if (!self && !java_thread->is_suspended() && !java_thread->is_carrier_thread_suspended()) {
2090     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2091     return;
2092   }
2093 
2094   // Check to see if a PopFrame was already in progress
2095   if (java_thread->popframe_condition() != JavaThread::popframe_inactive) {
2096     // Probably possible for JVMTI clients to trigger this, but the
2097     // JPDA backend shouldn't allow this to happen
2098     _result = JVMTI_ERROR_INTERNAL;
2099     return;
2100   }
2101 
2102   // Was workaround bug
2103   //    4812902: popFrame hangs if the method is waiting at a synchronize
2104   // Catch this condition and return an error to avoid hanging.
2105   // Now JVMTI spec allows an implementation to bail out with an opaque frame error.
2106   OSThread* osThread = java_thread->osthread();
2107   if (osThread->get_state() == MONITOR_WAIT) {
2108     _result = JVMTI_ERROR_OPAQUE_FRAME;
2109     return;
2110   }
2111 
2112   ResourceMark rm(current_thread);
2113   // Check if there is more than one Java frame in this thread, that the top two frames
2114   // are Java (not native) frames, and that there is no intervening VM frame
2115   int frame_count = 0;
2116   bool is_interpreted[2];
2117   intptr_t *frame_sp[2];
2118   // The 2-nd arg of constructor is needed to stop iterating at java entry frame.
2119   for (vframeStream vfs(java_thread, true, false /* process_frames */); !vfs.at_end(); vfs.next()) {
2120     methodHandle mh(current_thread, vfs.method());
2121     if (mh->is_native()) {
2122       _result = JVMTI_ERROR_OPAQUE_FRAME;
2123       return;
2124     }
2125     is_interpreted[frame_count] = vfs.is_interpreted_frame();
2126     frame_sp[frame_count] = vfs.frame_id();
2127     if (++frame_count > 1) break;
2128   }
2129   if (frame_count < 2)  {
2130     // We haven't found two adjacent non-native Java frames on the top.
2131     // There can be two situations here:
2132     //  1. There are no more java frames
2133     //  2. Two top java frames are separated by non-java native frames
2134     if (JvmtiEnvBase::jvf_for_thread_and_depth(java_thread, 1) == NULL) {
2135       _result = JVMTI_ERROR_NO_MORE_FRAMES;
2136       return;
2137     } else {
2138       // Intervening non-java native or VM frames separate java frames.
2139       // Current implementation does not support this. See bug #5031735.
2140       // In theory it is possible to pop frames in such cases.
2141       _result = JVMTI_ERROR_OPAQUE_FRAME;
2142       return;
2143     }
2144   }
2145 
2146   // If any of the top 2 frames is a compiled one, need to deoptimize it
2147   for (int i = 0; i < 2; i++) {
2148     if (!is_interpreted[i]) {
2149       Deoptimization::deoptimize_frame(java_thread, frame_sp[i]);
2150     }
2151   }
2152 
2153   // Update the thread state to reflect that the top frame is popped
2154   // so that cur_stack_depth is maintained properly and all frameIDs
2155   // are invalidated.
2156   // The current frame will be popped later when the suspended thread
2157   // is resumed and right before returning from VM to Java.
2158   // (see call_VM_base() in assembler_<cpu>.cpp).
2159 
2160   // It's fine to update the thread state here because no JVMTI events
2161   // shall be posted for this PopFrame.
2162 
2163   _state->update_for_pop_top_frame();
2164   java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
2165   // Set pending step flag for this popframe and it is cleared when next
2166   // step event is posted.
2167   _state->set_pending_step_for_popframe();
2168   _result = JVMTI_ERROR_NONE;
2169 }
2170 
2171 void
2172 SetFramePopClosure::doit(Thread *target, bool self) {
2173   ResourceMark rm;
2174   JavaThread* java_thread = JavaThread::cast(target);
2175 
2176   if (java_thread->is_exiting()) {
2177     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2178   }
2179   assert(_state->get_thread_or_saved() == java_thread, "Must be");
2180 
2181   if (!self && !java_thread->is_suspended()) {
2182     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2183     return;
2184   }
2185   if (!java_thread->has_last_Java_frame()) {
2186     _result = JVMTI_ERROR_NO_MORE_FRAMES;
2187     return;
2188   }
2189   RegisterMap reg_map(java_thread,
2190                       RegisterMap::UpdateMap::include,
2191                       RegisterMap::ProcessFrames::skip,
2192                       RegisterMap::WalkContinuation::include);
2193   javaVFrame* jvf = JvmtiEnvBase::get_cthread_last_java_vframe(java_thread, &reg_map);
2194   _result = ((JvmtiEnvBase*)_env)->set_frame_pop(_state, jvf, _depth);
2195 }
2196 
2197 void
2198 GetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2199   JavaThread *jt = JavaThread::cast(target);
2200   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
2201     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread,
2202                                                          jt,
2203                                                          _owned_monitors_list);
2204   }
2205 }
2206 
2207 void
2208 GetCurrentContendedMonitorClosure::do_thread(Thread *target) {
2209   JavaThread *jt = JavaThread::cast(target);
2210   if (!jt->is_exiting() && (jt->threadObj() != NULL)) {
2211     _result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor(_calling_thread,
2212                                                                     jt,
2213                                                                     _owned_monitor_ptr,
2214                                                                     _is_virtual);
2215   }
2216 }
2217 
2218 void
2219 VM_VirtualThreadGetStackTrace::doit() {
2220   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2221     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2222     return;
2223   }
2224   ResourceMark rm;
2225   javaVFrame* jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2226 
2227   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2228                                                     _start_depth, _max_count,
2229                                                     _frame_buffer, _count_ptr);
2230 }
2231 
2232 void
2233 GetStackTraceClosure::do_thread(Thread *target) {
2234   JavaThread *jt = JavaThread::cast(target);
2235   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2236     _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jt,
2237                                                       _start_depth, _max_count,
2238                                                       _frame_buffer, _count_ptr);
2239   }
2240 }
2241 
2242 #ifdef ASSERT
2243 void
2244 PrintStackTraceClosure::do_thread_impl(Thread *target) {
2245   JavaThread *java_thread = JavaThread::cast(target);
2246   Thread *current_thread = Thread::current();
2247 
2248   ResourceMark rm (current_thread);
2249   const char* tname = JvmtiTrace::safe_get_thread_name(java_thread);
2250   oop t_oop = java_thread->jvmti_vthread();
2251   t_oop = t_oop == NULL ? java_thread->threadObj() : t_oop;
2252   bool is_vt_suspended = java_lang_VirtualThread::is_instance(t_oop) && JvmtiVTSuspender::is_vthread_suspended(t_oop);
2253 
2254   log_error(jvmti)("%s(%s) exiting: %d is_susp: %d is_thread_susp: %d is_vthread_susp: %d "
2255                    "is_VTMS_transition_disabler: %d, is_in_VTMS_transition = %d\n",
2256                    tname, java_thread->name(), java_thread->is_exiting(),
2257                    java_thread->is_suspended(), java_thread->is_carrier_thread_suspended(), is_vt_suspended,
2258                    java_thread->is_VTMS_transition_disabler(), java_thread->is_in_VTMS_transition());
2259 
2260   if (java_thread->has_last_Java_frame()) {
2261     RegisterMap reg_map(java_thread,
2262                         RegisterMap::UpdateMap::include,
2263                         RegisterMap::ProcessFrames::include,
2264                         RegisterMap::WalkContinuation::skip);
2265     ResourceMark rm(current_thread);
2266     HandleMark hm(current_thread);
2267     javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
2268     while (jvf != NULL) {
2269       log_error(jvmti)("  %s:%d",
2270                        jvf->method()->external_name(),
2271                        jvf->method()->line_number_from_bci(jvf->bci()));
2272       jvf = jvf->java_sender();
2273     }
2274   }
2275   log_error(jvmti)("\n");
2276 }
2277 
2278 void
2279 PrintStackTraceClosure::do_thread(Thread *target) {
2280   JavaThread *java_thread = JavaThread::cast(target);
2281   Thread *current_thread = Thread::current();
2282 
2283   assert(SafepointSynchronize::is_at_safepoint() ||
2284          java_thread->is_handshake_safe_for(current_thread),
2285          "call by myself / at safepoint / at handshake");
2286 
2287   PrintStackTraceClosure::do_thread_impl(target);
2288 }
2289 #endif
2290 
2291 void
2292 VM_VirtualThreadGetFrameCount::doit() {
2293   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2294 }
2295 
2296 void
2297 GetFrameCountClosure::do_thread(Thread *target) {
2298   JavaThread* jt = JavaThread::cast(target);
2299   assert(target == jt, "just checking");
2300   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2301     _result = ((JvmtiEnvBase*)_env)->get_frame_count(jt, _count_ptr);
2302   }
2303 }
2304 
2305 void
2306 GetFrameLocationClosure::do_thread(Thread *target) {
2307   JavaThread *jt = JavaThread::cast(target);
2308   if (!jt->is_exiting() && jt->threadObj() != NULL) {
2309     _result = ((JvmtiEnvBase*)_env)->get_frame_location(jt, _depth,
2310                                                         _method_ptr, _location_ptr);
2311   }
2312 }
2313 
2314 void
2315 VirtualThreadGetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2316   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2317     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2318     return;
2319   }
2320   JavaThread* java_thread = JavaThread::cast(target);
2321   Thread* cur_thread = Thread::current();
2322   ResourceMark rm(cur_thread);
2323   HandleMark hm(cur_thread);
2324 
2325   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2326 
2327   if (!java_thread->is_exiting() && java_thread->threadObj() != NULL) {
2328     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors((JavaThread*)target,
2329                                                          java_thread,
2330                                                          jvf,
2331                                                          _owned_monitors_list);
2332   }
2333 }
2334 
2335 void
2336 VirtualThreadGetThreadClosure::do_thread(Thread *target) {
2337   assert(target->is_Java_thread(), "just checking");
2338   JavaThread *jt = JavaThread::cast(target);
2339   oop carrier_thread = java_lang_VirtualThread::carrier_thread(_vthread_h());
2340   *_carrier_thread_ptr = (jthread)JNIHandles::make_local(jt, carrier_thread);
2341 }
2342 
2343 void
2344 VirtualThreadGetStackTraceClosure::do_thread(Thread *target) {
2345   assert(target->is_Java_thread(), "just checking");
2346   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2347     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2348     return;
2349   }
2350   Thread* cur_thread = Thread::current();
2351   ResourceMark rm(cur_thread);
2352   HandleMark hm(cur_thread);
2353 
2354   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2355   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2356                                                     _start_depth, _max_count,
2357                                                     _frame_buffer, _count_ptr);
2358 }
2359 
2360 void
2361 VirtualThreadGetFrameCountClosure::do_thread(Thread *target) {
2362   assert(target->is_Java_thread(), "just checking");
2363   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2364 }
2365 
2366 void
2367 VirtualThreadGetFrameLocationClosure::do_thread(Thread *target) {
2368   assert(target->is_Java_thread(), "just checking");
2369   _result = ((JvmtiEnvBase*)_env)->get_frame_location(_vthread_h(), _depth,
2370                                                       _method_ptr, _location_ptr);
2371 }
2372 
2373 void
2374 VirtualThreadGetThreadStateClosure::do_thread(Thread *target) {
2375   assert(target->is_Java_thread(), "just checking");
2376   jshort vthread_state = java_lang_VirtualThread::state(_vthread_h());
2377   oop carrier_thread_oop = java_lang_VirtualThread::carrier_thread(_vthread_h());
2378   jint state;
2379 
2380   if (vthread_state == java_lang_VirtualThread::RUNNING && carrier_thread_oop != NULL) {
2381     state = (jint) java_lang_Thread::get_thread_status(carrier_thread_oop);
2382     JavaThread* java_thread = java_lang_Thread::thread(carrier_thread_oop);
2383     if (java_thread->is_suspended()) {
2384       state |= JVMTI_THREAD_STATE_SUSPENDED;
2385     }
2386   } else {
2387     state = (jint) java_lang_VirtualThread::map_state_to_thread_status(vthread_state);
2388   }
2389   if (java_lang_Thread::interrupted(_vthread_h())) {
2390     state |= JVMTI_THREAD_STATE_INTERRUPTED;
2391   }
2392   *_state_ptr = state;
2393   _result = JVMTI_ERROR_NONE;
2394 }
2395 
2396 void
2397 VirtualThreadSetFramePopClosure::doit(Thread *target, bool self) {
2398   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2399     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2400     return;
2401   }
2402   if (!self && !JvmtiVTSuspender::is_vthread_suspended(_vthread_h())) {
2403     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2404     return;
2405   }
2406   ResourceMark rm;
2407   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2408   _result = ((JvmtiEnvBase*)_env)->set_frame_pop(_state, jvf, _depth);
2409 }