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