1 /*
   2  * Copyright (c) 2003, 2023, 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   jint 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   return java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::NEW &&
 629          java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::TERMINATED;
 630 }
 631 
 632 // Return JavaThread if virtual thread is mounted, null otherwise.
 633 JavaThread* JvmtiEnvBase::get_JavaThread_or_null(oop vthread) {
 634   oop carrier_thread = java_lang_VirtualThread::carrier_thread(vthread);
 635   if (carrier_thread == nullptr) {
 636     return nullptr;
 637   }
 638 
 639   JavaThread* java_thread = java_lang_Thread::thread(carrier_thread);
 640 
 641   // This could be a different thread to the current one. So we need to ensure that
 642   // processing has started before we are allowed to read the continuation oop of
 643   // another thread, as it is a direct root of that other thread.
 644   StackWatermarkSet::start_processing(java_thread, StackWatermarkKind::gc);
 645 
 646   oop cont = java_lang_VirtualThread::continuation(vthread);
 647   assert(cont != nullptr, "must be");
 648   assert(Continuation::continuation_scope(cont) == java_lang_VirtualThread::vthread_scope(), "must be");
 649   return Continuation::is_continuation_mounted(java_thread, cont) ? java_thread : nullptr;
 650 }
 651 
 652 javaVFrame*
 653 JvmtiEnvBase::check_and_skip_hidden_frames(bool is_in_VTMS_transition, javaVFrame* jvf) {
 654   // The second condition is needed to hide notification methods.
 655   if (!is_in_VTMS_transition && (jvf == nullptr || !jvf->method()->jvmti_mount_transition())) {
 656     return jvf;  // No frames to skip.
 657   }
 658   // Find jvf with a method annotated with @JvmtiMountTransition.
 659   for ( ; jvf != nullptr; jvf = jvf->java_sender()) {
 660     if (jvf->method()->jvmti_mount_transition()) {  // Cannot actually appear in an unmounted continuation; they're never frozen.
 661       jvf = jvf->java_sender();  // Skip annotated method.
 662       break;
 663     }
 664     if (jvf->method()->changes_current_thread()) {
 665       break;
 666     }
 667     // Skip frame above annotated method.
 668   }
 669   return jvf;
 670 }
 671 
 672 javaVFrame*
 673 JvmtiEnvBase::check_and_skip_hidden_frames(JavaThread* jt, javaVFrame* jvf) {
 674   jvf = check_and_skip_hidden_frames(jt->is_in_VTMS_transition(), jvf);
 675   return jvf;
 676 }
 677 
 678 javaVFrame*
 679 JvmtiEnvBase::check_and_skip_hidden_frames(oop vthread, javaVFrame* jvf) {
 680   JvmtiThreadState* state = java_lang_Thread::jvmti_thread_state(vthread);
 681   if (state == nullptr) {
 682     // nothing to skip
 683     return jvf;
 684   }
 685   jvf = check_and_skip_hidden_frames(java_lang_Thread::is_in_VTMS_transition(vthread), jvf);
 686   return jvf;
 687 }
 688 
 689 javaVFrame*
 690 JvmtiEnvBase::get_vthread_jvf(oop vthread) {
 691   assert(java_lang_VirtualThread::state(vthread) != java_lang_VirtualThread::NEW, "sanity check");
 692   assert(java_lang_VirtualThread::state(vthread) != java_lang_VirtualThread::TERMINATED, "sanity check");
 693 
 694   Thread* cur_thread = Thread::current();
 695   oop cont = java_lang_VirtualThread::continuation(vthread);
 696   javaVFrame* jvf = nullptr;
 697 
 698   JavaThread* java_thread = get_JavaThread_or_null(vthread);
 699   if (java_thread != nullptr) {
 700     if (!java_thread->has_last_Java_frame()) {
 701       // TBD: This is a temporary work around to avoid a guarantee caused by
 702       // the native enterSpecial frame on the top. No frames will be found
 703       // by the JVMTI functions such as GetStackTrace.
 704       return nullptr;
 705     }
 706     vframeStream vfs(java_thread);
 707     jvf = vfs.at_end() ? nullptr : vfs.asJavaVFrame();
 708     jvf = check_and_skip_hidden_frames(java_thread, jvf);
 709   } else {
 710     vframeStream vfs(cont);
 711     jvf = vfs.at_end() ? nullptr : vfs.asJavaVFrame();
 712     jvf = check_and_skip_hidden_frames(vthread, jvf);
 713   }
 714   return jvf;
 715 }
 716 
 717 // Return correct javaVFrame for a carrier (non-virtual) thread.
 718 // It strips vthread frames at the top if there are any.
 719 javaVFrame*
 720 JvmtiEnvBase::get_cthread_last_java_vframe(JavaThread* jt, RegisterMap* reg_map_p) {
 721   // Strip vthread frames in case of carrier thread with mounted continuation.
 722   bool cthread_with_cont = JvmtiEnvBase::is_cthread_with_continuation(jt);
 723   javaVFrame *jvf = cthread_with_cont ? jt->carrier_last_java_vframe(reg_map_p)
 724                                       : jt->last_java_vframe(reg_map_p);
 725   // Skip hidden frames only for carrier threads
 726   // which are in non-temporary VTMS transition.
 727   if (jt->is_in_VTMS_transition()) {
 728     jvf = check_and_skip_hidden_frames(jt, jvf);
 729   }
 730   return jvf;
 731 }
 732 
 733 jint
 734 JvmtiEnvBase::get_thread_state_base(oop thread_oop, JavaThread* jt) {
 735   jint state = 0;
 736 
 737   if (thread_oop != nullptr) {
 738     // Get most state bits.
 739     state = (jint)java_lang_Thread::get_thread_status(thread_oop);
 740   }
 741   if (jt != nullptr) {
 742     // We have a JavaThread* so add more state bits.
 743     JavaThreadState jts = jt->thread_state();
 744 
 745     if (jt->is_carrier_thread_suspended() ||
 746         ((jt->jvmti_vthread() == nullptr || jt->jvmti_vthread() == thread_oop) && jt->is_suspended())) {
 747       // Suspended non-virtual thread.
 748       state |= JVMTI_THREAD_STATE_SUSPENDED;
 749     }
 750     if (jts == _thread_in_native) {
 751       state |= JVMTI_THREAD_STATE_IN_NATIVE;
 752     }
 753     if (jt->is_interrupted(false)) {
 754       state |= JVMTI_THREAD_STATE_INTERRUPTED;
 755     }
 756   }
 757   return state;
 758 }
 759 
 760 jint
 761 JvmtiEnvBase::get_thread_state(oop thread_oop, JavaThread* jt) {
 762   jint state = 0;
 763 
 764   if (is_thread_carrying_vthread(jt, thread_oop)) {
 765     state = (jint)java_lang_Thread::get_thread_status(thread_oop);
 766 
 767     // This is for extra safety. Other bits are not expected nor needed.
 768     state &= (JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_INTERRUPTED);
 769 
 770     if (jt->is_carrier_thread_suspended()) {
 771       state |= JVMTI_THREAD_STATE_SUSPENDED;
 772     }
 773     // It's okay for the JVMTI state to be reported as WAITING when waiting
 774     // for something other than an Object.wait. So, we treat a thread carrying
 775     // a virtual thread as waiting indefinitely which is not runnable.
 776     // It is why the RUNNABLE bit is not needed and the WAITING bits are added.
 777     state |= JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_INDEFINITELY;
 778   } else {
 779     state = get_thread_state_base(thread_oop, jt);
 780   }
 781   return state;
 782 }
 783 
 784 jint
 785 JvmtiEnvBase::get_vthread_state(oop thread_oop, JavaThread* java_thread) {
 786   jint state = 0;
 787   bool ext_suspended = JvmtiVTSuspender::is_vthread_suspended(thread_oop);
 788   jint interrupted = java_lang_Thread::interrupted(thread_oop);
 789 
 790   if (java_thread != nullptr) {
 791     // If virtual thread is blocked on a monitor enter the BLOCKED_ON_MONITOR_ENTER bit
 792     // is set for carrier thread instead of virtual.
 793     // Other state bits except filtered ones are expected to be the same.
 794     oop ct_oop = java_lang_VirtualThread::carrier_thread(thread_oop);
 795     jint filtered_bits = JVMTI_THREAD_STATE_SUSPENDED | JVMTI_THREAD_STATE_INTERRUPTED;
 796 
 797     // This call can trigger a safepoint, so thread_oop must not be used after it.
 798     state = get_thread_state_base(ct_oop, java_thread) & ~filtered_bits;
 799   } else {
 800     jshort vt_state = java_lang_VirtualThread::state(thread_oop);
 801     state = (jint)java_lang_VirtualThread::map_state_to_thread_status(vt_state);
 802   }
 803   if (ext_suspended && ((state & JVMTI_THREAD_STATE_ALIVE) != 0)) {
 804     state &= ~java_lang_VirtualThread::RUNNING;
 805     state |= JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE | JVMTI_THREAD_STATE_SUSPENDED;
 806   }
 807   if (interrupted) {
 808     state |= JVMTI_THREAD_STATE_INTERRUPTED;
 809   }
 810   return state;
 811 }
 812 
 813 jvmtiError
 814 JvmtiEnvBase::get_live_threads(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, Handle **thread_objs_p) {
 815   jint count = 0;
 816   Handle *thread_objs = nullptr;
 817   ThreadsListEnumerator tle(current_thread, /* include_jvmti_agent_threads */ true);
 818   int nthreads = tle.num_threads();
 819   if (nthreads > 0) {
 820     thread_objs = NEW_RESOURCE_ARRAY_RETURN_NULL(Handle, nthreads);
 821     NULL_CHECK(thread_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 822     for (int i = 0; i < nthreads; i++) {
 823       Handle thread = tle.get_threadObj(i);
 824       if (thread()->is_a(vmClasses::Thread_klass()) && java_lang_Thread::threadGroup(thread()) == group_hdl()) {
 825         thread_objs[count++] = thread;
 826       }
 827     }
 828   }
 829   *thread_objs_p = thread_objs;
 830   *count_ptr = count;
 831   return JVMTI_ERROR_NONE;
 832 }
 833 
 834 jvmtiError
 835 JvmtiEnvBase::get_subgroups(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, objArrayHandle *group_objs_p) {
 836 
 837   // This call collects the strong and weak groups
 838   JavaThread* THREAD = current_thread;
 839   JavaValue result(T_OBJECT);
 840   JavaCalls::call_virtual(&result,
 841                           group_hdl,
 842                           vmClasses::ThreadGroup_klass(),
 843                           SymbolTable::new_permanent_symbol("subgroupsAsArray"),
 844                           vmSymbols::void_threadgroup_array_signature(),
 845                           THREAD);
 846   if (HAS_PENDING_EXCEPTION) {
 847     Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
 848     CLEAR_PENDING_EXCEPTION;
 849     if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
 850       return JVMTI_ERROR_OUT_OF_MEMORY;
 851     } else {
 852       return JVMTI_ERROR_INTERNAL;
 853     }
 854   }
 855 
 856   assert(result.get_type() == T_OBJECT, "just checking");
 857   objArrayOop groups = (objArrayOop)result.get_oop();
 858 
 859   *count_ptr = groups == nullptr ? 0 : groups->length();
 860   *group_objs_p = objArrayHandle(current_thread, groups);
 861 
 862   return JVMTI_ERROR_NONE;
 863 }
 864 
 865 //
 866 // Object Monitor Information
 867 //
 868 
 869 //
 870 // Count the number of objects for a lightweight monitor. The hobj
 871 // parameter is object that owns the monitor so this routine will
 872 // count the number of times the same object was locked by frames
 873 // in java_thread.
 874 //
 875 jint
 876 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
 877   jint ret = 0;
 878   if (!java_thread->has_last_Java_frame()) {
 879     return ret;  // no Java frames so no monitors
 880   }
 881 
 882   Thread* current_thread = Thread::current();
 883   ResourceMark rm(current_thread);
 884   HandleMark   hm(current_thread);
 885   RegisterMap  reg_map(java_thread,
 886                        RegisterMap::UpdateMap::include,
 887                        RegisterMap::ProcessFrames::include,
 888                        RegisterMap::WalkContinuation::skip);
 889 
 890   for (javaVFrame *jvf = java_thread->last_java_vframe(&reg_map); jvf != nullptr;
 891        jvf = jvf->java_sender()) {
 892     GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 893     if (!mons->is_empty()) {
 894       for (int i = 0; i < mons->length(); i++) {
 895         MonitorInfo *mi = mons->at(i);
 896         if (mi->owner_is_scalar_replaced()) continue;
 897 
 898         // see if owner of the monitor is our object
 899         if (mi->owner() != nullptr && mi->owner() == hobj()) {
 900           ret++;
 901         }
 902       }
 903     }
 904   }
 905   return ret;
 906 }
 907 
 908 jvmtiError
 909 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread,
 910                                             jobject *monitor_ptr, bool is_virtual) {
 911   Thread *current_thread = Thread::current();
 912   assert(java_thread->is_handshake_safe_for(current_thread),
 913          "call by myself or at handshake");
 914   if (!is_virtual && JvmtiEnvBase::is_cthread_with_continuation(java_thread)) {
 915     // Carrier thread with a mounted continuation case.
 916     // No contended monitor can be owned by carrier thread in this case.
 917     *monitor_ptr = nullptr;
 918     return JVMTI_ERROR_NONE;
 919   }
 920   oop obj = nullptr;
 921   // The ObjectMonitor* can't be async deflated since we are either
 922   // at a safepoint or the calling thread is operating on itself so
 923   // it cannot leave the underlying wait()/enter() call.
 924   ObjectMonitor *mon = java_thread->current_waiting_monitor();
 925   if (mon == nullptr) {
 926     // thread is not doing an Object.wait() call
 927     mon = java_thread->current_pending_monitor();
 928     if (mon != nullptr) {
 929       // The thread is trying to enter() an ObjectMonitor.
 930       obj = mon->object();
 931       assert(obj != nullptr, "ObjectMonitor should have a valid object!");
 932     }
 933     // implied else: no contended ObjectMonitor
 934   } else {
 935     // thread is doing an Object.wait() call
 936     obj = mon->object();
 937     assert(obj != nullptr, "Object.wait() should have an object");
 938   }
 939 
 940   if (obj == nullptr) {
 941     *monitor_ptr = nullptr;
 942   } else {
 943     HandleMark hm(current_thread);
 944     Handle     hobj(current_thread, obj);
 945     *monitor_ptr = jni_reference(calling_thread, hobj);
 946   }
 947   return JVMTI_ERROR_NONE;
 948 }
 949 
 950 jvmtiError
 951 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
 952                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 953   // Note:
 954   // calling_thread is the thread that requested the list of monitors for java_thread.
 955   // java_thread is the thread owning the monitors.
 956   // current_thread is the thread executing this code, can be a non-JavaThread (e.g. VM Thread).
 957   // And they all may be different threads.
 958   jvmtiError err = JVMTI_ERROR_NONE;
 959   Thread *current_thread = Thread::current();
 960   assert(java_thread->is_handshake_safe_for(current_thread),
 961          "call by myself or at handshake");
 962 
 963   if (JvmtiEnvBase::is_cthread_with_continuation(java_thread)) {
 964     // Carrier thread with a mounted continuation case.
 965     // No contended monitor can be owned by carrier thread in this case.
 966     return JVMTI_ERROR_NONE;
 967   }
 968   if (java_thread->has_last_Java_frame()) {
 969     ResourceMark rm(current_thread);
 970     HandleMark   hm(current_thread);
 971     RegisterMap  reg_map(java_thread,
 972                          RegisterMap::UpdateMap::include,
 973                          RegisterMap::ProcessFrames::include,
 974                          RegisterMap::WalkContinuation::skip);
 975 
 976     int depth = 0;
 977     for (javaVFrame *jvf = get_cthread_last_java_vframe(java_thread, &reg_map);
 978          jvf != nullptr; jvf = jvf->java_sender()) {
 979       if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 980         // add locked objects for this frame into list
 981         err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 982         if (err != JVMTI_ERROR_NONE) {
 983           return err;
 984         }
 985       }
 986     }
 987   }
 988 
 989   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 990   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
 991   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
 992   err = jmc.error();
 993 
 994   return err;
 995 }
 996 
 997 jvmtiError
 998 JvmtiEnvBase::get_owned_monitors(JavaThread* calling_thread, JavaThread* java_thread, javaVFrame* jvf,
 999                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
1000   jvmtiError err = JVMTI_ERROR_NONE;
1001   Thread *current_thread = Thread::current();
1002   assert(java_thread->is_handshake_safe_for(current_thread),
1003          "call by myself or at handshake");
1004 
1005   int depth = 0;
1006   for ( ; jvf != nullptr; jvf = jvf->java_sender()) {
1007     if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
1008       // Add locked objects for this frame into list.
1009       err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth - 1);
1010       if (err != JVMTI_ERROR_NONE) {
1011         return err;
1012       }
1013     }
1014   }
1015 
1016   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
1017   JvmtiMonitorClosure jmc(calling_thread, owned_monitors_list, this);
1018   ObjectSynchronizer::monitors_iterate(&jmc, java_thread);
1019   err = jmc.error();
1020 
1021   return err;
1022 }
1023 
1024 // Save JNI local handles for any objects that this frame owns.
1025 jvmtiError
1026 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
1027                                  javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, jint stack_depth) {
1028   jvmtiError err = JVMTI_ERROR_NONE;
1029   Thread* current_thread = Thread::current();
1030   ResourceMark rm(current_thread);
1031   HandleMark   hm(current_thread);
1032 
1033   GrowableArray<MonitorInfo*>* mons = jvf->monitors();
1034   if (mons->is_empty()) {
1035     return err;  // this javaVFrame holds no monitors
1036   }
1037 
1038   oop wait_obj = nullptr;
1039   {
1040     // The ObjectMonitor* can't be async deflated since we are either
1041     // at a safepoint or the calling thread is operating on itself so
1042     // it cannot leave the underlying wait() call.
1043     // Save object of current wait() call (if any) for later comparison.
1044     ObjectMonitor *mon = java_thread->current_waiting_monitor();
1045     if (mon != nullptr) {
1046       wait_obj = mon->object();
1047     }
1048   }
1049   oop pending_obj = nullptr;
1050   {
1051     // The ObjectMonitor* can't be async deflated since we are either
1052     // at a safepoint or the calling thread is operating on itself so
1053     // it cannot leave the underlying enter() call.
1054     // Save object of current enter() call (if any) for later comparison.
1055     ObjectMonitor *mon = java_thread->current_pending_monitor();
1056     if (mon != nullptr) {
1057       pending_obj = mon->object();
1058     }
1059   }
1060 
1061   for (int i = 0; i < mons->length(); i++) {
1062     MonitorInfo *mi = mons->at(i);
1063 
1064     if (mi->owner_is_scalar_replaced()) continue;
1065 
1066     oop obj = mi->owner();
1067     if (obj == nullptr) {
1068       // this monitor doesn't have an owning object so skip it
1069       continue;
1070     }
1071 
1072     if (wait_obj == obj) {
1073       // the thread is waiting on this monitor so it isn't really owned
1074       continue;
1075     }
1076 
1077     if (pending_obj == obj) {
1078       // the thread is pending on this monitor so it isn't really owned
1079       continue;
1080     }
1081 
1082     if (owned_monitors_list->length() > 0) {
1083       // Our list has at least one object on it so we have to check
1084       // for recursive object locking
1085       bool found = false;
1086       for (int j = 0; j < owned_monitors_list->length(); j++) {
1087         jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
1088         oop check = JNIHandles::resolve(jobj);
1089         if (check == obj) {
1090           found = true;  // we found the object
1091           break;
1092         }
1093       }
1094 
1095       if (found) {
1096         // already have this object so don't include it
1097         continue;
1098       }
1099     }
1100 
1101     // add the owning object to our list
1102     jvmtiMonitorStackDepthInfo *jmsdi;
1103     err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1104     if (err != JVMTI_ERROR_NONE) {
1105         return err;
1106     }
1107     Handle hobj(Thread::current(), obj);
1108     jmsdi->monitor = jni_reference(calling_thread, hobj);
1109     jmsdi->stack_depth = stack_depth;
1110     owned_monitors_list->append(jmsdi);
1111   }
1112 
1113   return err;
1114 }
1115 
1116 jvmtiError
1117 JvmtiEnvBase::get_stack_trace(javaVFrame *jvf,
1118                               jint start_depth, jint max_count,
1119                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1120   Thread *current_thread = Thread::current();
1121   ResourceMark rm(current_thread);
1122   HandleMark hm(current_thread);
1123   int count = 0;
1124 
1125   if (start_depth != 0) {
1126     if (start_depth > 0) {
1127       for (int j = 0; j < start_depth && jvf != nullptr; j++) {
1128         jvf = jvf->java_sender();
1129       }
1130       if (jvf == nullptr) {
1131         // start_depth is deeper than the stack depth.
1132         return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1133       }
1134     } else { // start_depth < 0
1135       // We are referencing the starting depth based on the oldest
1136       // part of the stack.
1137       // Optimize to limit the number of times that java_sender() is called.
1138       javaVFrame *jvf_cursor = jvf;
1139       javaVFrame *jvf_prev = nullptr;
1140       javaVFrame *jvf_prev_prev = nullptr;
1141       int j = 0;
1142       while (jvf_cursor != nullptr) {
1143         jvf_prev_prev = jvf_prev;
1144         jvf_prev = jvf_cursor;
1145         for (j = 0; j > start_depth && jvf_cursor != nullptr; j--) {
1146           jvf_cursor = jvf_cursor->java_sender();
1147         }
1148       }
1149       if (j == start_depth) {
1150         // Previous pointer is exactly where we want to start.
1151         jvf = jvf_prev;
1152       } else {
1153         // We need to back up further to get to the right place.
1154         if (jvf_prev_prev == nullptr) {
1155           // The -start_depth is greater than the stack depth.
1156           return JVMTI_ERROR_ILLEGAL_ARGUMENT;
1157         }
1158         // j is now the number of frames on the stack starting with
1159         // jvf_prev, we start from jvf_prev_prev and move older on
1160         // the stack that many, and the result is -start_depth frames
1161         // remaining.
1162         jvf = jvf_prev_prev;
1163         for (; j < 0; j++) {
1164           jvf = jvf->java_sender();
1165         }
1166       }
1167     }
1168   }
1169   for (; count < max_count && jvf != nullptr; count++) {
1170     frame_buffer[count].method = jvf->method()->jmethod_id();
1171     frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
1172     jvf = jvf->java_sender();
1173   }
1174   *count_ptr = count;
1175   return JVMTI_ERROR_NONE;
1176 }
1177 
1178 jvmtiError
1179 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
1180                               jint start_depth, jint max_count,
1181                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1182   Thread *current_thread = Thread::current();
1183   assert(SafepointSynchronize::is_at_safepoint() ||
1184          java_thread->is_handshake_safe_for(current_thread),
1185          "call by myself / at safepoint / at handshake");
1186   int count = 0;
1187   jvmtiError err = JVMTI_ERROR_NONE;
1188 
1189   if (java_thread->has_last_Java_frame()) {
1190     RegisterMap reg_map(java_thread,
1191                         RegisterMap::UpdateMap::include,
1192                         RegisterMap::ProcessFrames::skip,
1193                         RegisterMap::WalkContinuation::skip);
1194     ResourceMark rm(current_thread);
1195     javaVFrame *jvf = get_cthread_last_java_vframe(java_thread, &reg_map);
1196 
1197     err = get_stack_trace(jvf, start_depth, max_count, frame_buffer, count_ptr);
1198   } else {
1199     *count_ptr = 0;
1200     if (start_depth != 0) {
1201       // no frames and there is a starting depth
1202       err = JVMTI_ERROR_ILLEGAL_ARGUMENT;
1203     }
1204   }
1205   return err;
1206 }
1207 
1208 jint
1209 JvmtiEnvBase::get_frame_count(javaVFrame *jvf) {
1210   int count = 0;
1211 
1212   while (jvf != nullptr) {
1213     jvf = jvf->java_sender();
1214     count++;
1215   }
1216   return count;
1217 }
1218 
1219 jvmtiError
1220 JvmtiEnvBase::get_frame_count(JavaThread* jt, jint *count_ptr) {
1221   Thread *current_thread = Thread::current();
1222   assert(current_thread == jt ||
1223          SafepointSynchronize::is_at_safepoint() ||
1224          jt->is_handshake_safe_for(current_thread),
1225          "call by myself / at safepoint / at handshake");
1226 
1227   if (!jt->has_last_Java_frame()) { // no Java frames
1228     *count_ptr = 0;
1229   } else {
1230     ResourceMark rm(current_thread);
1231     RegisterMap reg_map(jt,
1232                         RegisterMap::UpdateMap::include,
1233                         RegisterMap::ProcessFrames::include,
1234                         RegisterMap::WalkContinuation::skip);
1235     javaVFrame *jvf = get_cthread_last_java_vframe(jt, &reg_map);
1236 
1237     *count_ptr = get_frame_count(jvf);
1238   }
1239   return JVMTI_ERROR_NONE;
1240 }
1241 
1242 jvmtiError
1243 JvmtiEnvBase::get_frame_count(oop vthread_oop, jint *count_ptr) {
1244   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1245     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1246   }
1247   Thread *current_thread = Thread::current();
1248   ResourceMark rm(current_thread);
1249   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1250 
1251   *count_ptr = get_frame_count(jvf);
1252   return JVMTI_ERROR_NONE;
1253 }
1254 
1255 jvmtiError
1256 JvmtiEnvBase::get_frame_location(javaVFrame* jvf, jint depth,
1257                                  jmethodID* method_ptr, jlocation* location_ptr) {
1258   int cur_depth = 0;
1259 
1260   while (jvf != nullptr && cur_depth < depth) {
1261     jvf = jvf->java_sender();
1262     cur_depth++;
1263   }
1264   assert(depth >= cur_depth, "ran out of frames too soon");
1265   if (jvf == nullptr) {
1266     return JVMTI_ERROR_NO_MORE_FRAMES;
1267   }
1268   Method* method = jvf->method();
1269   if (method->is_native()) {
1270     *location_ptr = -1;
1271   } else {
1272     *location_ptr = jvf->bci();
1273   }
1274   *method_ptr = method->jmethod_id();
1275   return JVMTI_ERROR_NONE;
1276 }
1277 
1278 jvmtiError
1279 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
1280                                  jmethodID* method_ptr, jlocation* location_ptr) {
1281   Thread* current = Thread::current();
1282   assert(java_thread->is_handshake_safe_for(current),
1283          "call by myself or at handshake");
1284   if (!java_thread->has_last_Java_frame()) {
1285     return JVMTI_ERROR_NO_MORE_FRAMES;
1286   }
1287   ResourceMark rm(current);
1288   HandleMark hm(current);
1289   RegisterMap reg_map(java_thread,
1290                       RegisterMap::UpdateMap::include,
1291                       RegisterMap::ProcessFrames::skip,
1292                       RegisterMap::WalkContinuation::include);
1293   javaVFrame* jvf = JvmtiEnvBase::get_cthread_last_java_vframe(java_thread, &reg_map);
1294 
1295   return get_frame_location(jvf, depth, method_ptr, location_ptr);
1296 }
1297 
1298 jvmtiError
1299 JvmtiEnvBase::get_frame_location(oop vthread_oop, jint depth,
1300                                  jmethodID* method_ptr, jlocation* location_ptr) {
1301   if (!JvmtiEnvBase::is_vthread_alive(vthread_oop)) {
1302     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1303   }
1304   Thread* current = Thread::current();
1305   ResourceMark rm(current);
1306   HandleMark hm(current);
1307   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(vthread_oop);
1308 
1309   return get_frame_location(jvf, depth, method_ptr, location_ptr);
1310 }
1311 
1312 jvmtiError
1313 JvmtiEnvBase::set_frame_pop(JvmtiThreadState* state, javaVFrame* jvf, jint depth) {
1314   for (int d = 0; jvf != nullptr && d < depth; d++) {
1315     jvf = jvf->java_sender();
1316   }
1317   if (jvf == nullptr) {
1318     return JVMTI_ERROR_NO_MORE_FRAMES;
1319   }
1320   if (jvf->method()->is_native()) {
1321     return JVMTI_ERROR_OPAQUE_FRAME;
1322   }
1323   assert(jvf->frame_pointer() != nullptr, "frame pointer mustn't be null");
1324   int frame_number = (int)get_frame_count(jvf);
1325   state->env_thread_state((JvmtiEnvBase*)this)->set_frame_pop(frame_number);
1326   return JVMTI_ERROR_NONE;
1327 }
1328 
1329 bool
1330 JvmtiEnvBase::is_cthread_with_mounted_vthread(JavaThread* jt) {
1331   oop thread_oop = jt->threadObj();
1332   assert(thread_oop != nullptr, "sanity check");
1333   oop mounted_vt = jt->jvmti_vthread();
1334 
1335   return mounted_vt != nullptr && mounted_vt != thread_oop;
1336 }
1337 
1338 bool
1339 JvmtiEnvBase::is_cthread_with_continuation(JavaThread* jt) {
1340   const ContinuationEntry* cont_entry = nullptr;
1341   if (jt->has_last_Java_frame()) {
1342     cont_entry = jt->vthread_continuation();
1343   }
1344   return cont_entry != nullptr && is_cthread_with_mounted_vthread(jt);
1345 }
1346 
1347 // Check if VirtualThread or BoundVirtualThread is suspended.
1348 bool
1349 JvmtiEnvBase::is_vthread_suspended(oop vt_oop, JavaThread* jt) {
1350   bool suspended = false;
1351   if (java_lang_VirtualThread::is_instance(vt_oop)) {
1352     suspended = JvmtiVTSuspender::is_vthread_suspended(vt_oop);
1353   }
1354   if (vt_oop->is_a(vmClasses::BoundVirtualThread_klass())) {
1355     suspended = jt->is_suspended();
1356   }
1357   return suspended;
1358 }
1359 
1360 // If (thread == null) then return current thread object.
1361 // Otherwise return JNIHandles::resolve_external_guard(thread).
1362 oop
1363 JvmtiEnvBase::current_thread_obj_or_resolve_external_guard(jthread thread) {
1364   oop thread_obj = JNIHandles::resolve_external_guard(thread);
1365   if (thread == nullptr) {
1366     thread_obj = get_vthread_or_thread_oop(JavaThread::current());
1367   }
1368   return thread_obj;
1369 }
1370 
1371 jvmtiError
1372 JvmtiEnvBase::get_threadOop_and_JavaThread(ThreadsList* t_list, jthread thread, JavaThread* cur_thread,
1373                                            JavaThread** jt_pp, oop* thread_oop_p) {
1374   JavaThread* java_thread = nullptr;
1375   oop thread_oop = nullptr;
1376 
1377   if (thread == nullptr) {
1378     if (cur_thread == nullptr) { // cur_thread can be null when called from a VM_op
1379       return JVMTI_ERROR_INVALID_THREAD;
1380     }
1381     java_thread = cur_thread;
1382     thread_oop = get_vthread_or_thread_oop(java_thread);
1383     if (thread_oop == nullptr || !thread_oop->is_a(vmClasses::Thread_klass())) {
1384       return JVMTI_ERROR_INVALID_THREAD;
1385     }
1386   } else {
1387     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(t_list, thread, &java_thread, &thread_oop);
1388     if (err != JVMTI_ERROR_NONE) {
1389       // We got an error code so we don't have a JavaThread*, but only return
1390       // an error from here if we didn't get a valid thread_oop. In a vthread case
1391       // the cv_external_thread_to_JavaThread is expected to correctly set the
1392       // thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1393       if (thread_oop == nullptr || err != JVMTI_ERROR_INVALID_THREAD) {
1394         *thread_oop_p = thread_oop;
1395         return err;
1396       }
1397     }
1398     if (java_thread == nullptr && java_lang_VirtualThread::is_instance(thread_oop)) {
1399       java_thread = get_JavaThread_or_null(thread_oop);
1400     }
1401   }
1402   *jt_pp = java_thread;
1403   *thread_oop_p = thread_oop;
1404   if (java_lang_VirtualThread::is_instance(thread_oop) &&
1405       !JvmtiEnvBase::is_vthread_alive(thread_oop)) {
1406     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1407   }
1408   return JVMTI_ERROR_NONE;
1409 }
1410 
1411 jvmtiError
1412 JvmtiEnvBase::get_threadOop_and_JavaThread(ThreadsList* t_list, jthread thread,
1413                                            JavaThread** jt_pp, oop* thread_oop_p) {
1414   JavaThread* cur_thread = JavaThread::current();
1415   jvmtiError err = get_threadOop_and_JavaThread(t_list, thread, cur_thread, jt_pp, thread_oop_p);
1416   return err;
1417 }
1418 
1419 // Check for JVMTI_ERROR_NOT_SUSPENDED and JVMTI_ERROR_OPAQUE_FRAME errors.
1420 // Used in PopFrame and ForceEarlyReturn implementations.
1421 jvmtiError
1422 JvmtiEnvBase::check_non_suspended_or_opaque_frame(JavaThread* jt, oop thr_obj, bool self) {
1423   bool is_virtual = thr_obj != nullptr && thr_obj->is_a(vmClasses::BaseVirtualThread_klass());
1424 
1425   if (is_virtual) {
1426     if (!is_JavaThread_current(jt, thr_obj)) {
1427       if (!is_vthread_suspended(thr_obj, jt)) {
1428         return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1429       }
1430       if (jt == nullptr) { // unmounted virtual thread
1431         return JVMTI_ERROR_OPAQUE_FRAME;
1432       }
1433     }
1434   } else { // platform thread
1435     if (!self && !jt->is_suspended() &&
1436         !jt->is_carrier_thread_suspended()) {
1437       return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1438     }
1439   }
1440   return JVMTI_ERROR_NONE;
1441 }
1442 
1443 jvmtiError
1444 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
1445   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1446   Thread* current_thread = VMThread::vm_thread();
1447   assert(current_thread == Thread::current(), "must be");
1448 
1449   HandleMark hm(current_thread);
1450   Handle hobj;
1451 
1452   // Check arguments
1453   {
1454     oop mirror = JNIHandles::resolve_external_guard(object);
1455     NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
1456     NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
1457 
1458     hobj = Handle(current_thread, mirror);
1459   }
1460 
1461   ThreadsListHandle tlh(current_thread);
1462   JavaThread *owning_thread = nullptr;
1463   ObjectMonitor *mon = nullptr;
1464   jvmtiMonitorUsage ret = {
1465       nullptr, 0, 0, nullptr, 0, nullptr
1466   };
1467 
1468   uint32_t debug_bits = 0;
1469   // first derive the object's owner and entry_count (if any)
1470   owning_thread = ObjectSynchronizer::get_lock_owner(tlh.list(), hobj);
1471   if (owning_thread != nullptr) {
1472     Handle th(current_thread, get_vthread_or_thread_oop(owning_thread));
1473     ret.owner = (jthread)jni_reference(calling_thread, th);
1474 
1475     // The recursions field of a monitor does not reflect recursions
1476     // as lightweight locks before inflating the monitor are not included.
1477     // We have to count the number of recursive monitor entries the hard way.
1478     // We pass a handle to survive any GCs along the way.
1479     ret.entry_count = count_locked_objects(owning_thread, hobj);
1480   }
1481   // implied else: entry_count == 0
1482 
1483   jint nWant = 0, nWait = 0;
1484   markWord mark = hobj->mark();
1485   if (mark.has_monitor()) {
1486     mon = mark.monitor();
1487     assert(mon != nullptr, "must have monitor");
1488     // this object has a heavyweight monitor
1489     nWant = mon->contentions(); // # of threads contending for monitor
1490     nWait = mon->waiters();     // # of threads in Object.wait()
1491     ret.waiter_count = nWant + nWait;
1492     ret.notify_waiter_count = nWait;
1493   } else {
1494     // this object has a lightweight monitor
1495     ret.waiter_count = 0;
1496     ret.notify_waiter_count = 0;
1497   }
1498 
1499   // Allocate memory for heavyweight and lightweight monitor.
1500   jvmtiError err;
1501   err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
1502   if (err != JVMTI_ERROR_NONE) {
1503     return err;
1504   }
1505   err = allocate(ret.notify_waiter_count * sizeof(jthread *),
1506                  (unsigned char**)&ret.notify_waiters);
1507   if (err != JVMTI_ERROR_NONE) {
1508     deallocate((unsigned char*)ret.waiters);
1509     return err;
1510   }
1511 
1512   // now derive the rest of the fields
1513   if (mon != nullptr) {
1514     // this object has a heavyweight monitor
1515 
1516     // Number of waiters may actually be less than the waiter count.
1517     // So null out memory so that unused memory will be null.
1518     memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1519     memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1520 
1521     if (ret.waiter_count > 0) {
1522       // we have contending and/or waiting threads
1523       if (nWant > 0) {
1524         // we have contending threads
1525         ResourceMark rm(current_thread);
1526         // get_pending_threads returns only java thread so we do not need to
1527         // check for non java threads.
1528         GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(tlh.list(), nWant, (address)mon);
1529         if (wantList->length() < nWant) {
1530           // robustness: the pending list has gotten smaller
1531           nWant = wantList->length();
1532         }
1533         for (int i = 0; i < nWant; i++) {
1534           JavaThread *pending_thread = wantList->at(i);
1535           Handle th(current_thread, get_vthread_or_thread_oop(pending_thread));
1536           ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1537         }
1538       }
1539       if (nWait > 0) {
1540         // we have threads in Object.wait()
1541         int offset = nWant;  // add after any contending threads
1542         ObjectWaiter *waiter = mon->first_waiter();
1543         for (int i = 0, j = 0; i < nWait; i++) {
1544           if (waiter == nullptr) {
1545             // robustness: the waiting list has gotten smaller
1546             nWait = j;
1547             break;
1548           }
1549           JavaThread *w = mon->thread_of_waiter(waiter);
1550           if (w != nullptr) {
1551             // If the thread was found on the ObjectWaiter list, then
1552             // it has not been notified. This thread can't change the
1553             // state of the monitor so it doesn't need to be suspended.
1554             Handle th(current_thread, get_vthread_or_thread_oop(w));
1555             ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1556             ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1557           }
1558           waiter = mon->next_waiter(waiter);
1559         }
1560       }
1561     } // ThreadsListHandle is destroyed here.
1562 
1563     // Adjust count. nWant and nWait count values may be less than original.
1564     ret.waiter_count = nWant + nWait;
1565     ret.notify_waiter_count = nWait;
1566   } else {
1567     // this object has a lightweight monitor and we have nothing more
1568     // to do here because the defaults are just fine.
1569   }
1570 
1571   // we don't update return parameter unless everything worked
1572   *info_ptr = ret;
1573 
1574   return JVMTI_ERROR_NONE;
1575 }
1576 
1577 jvmtiError
1578 JvmtiEnvBase::check_thread_list(jint count, const jthread* list) {
1579   if (list == nullptr && count != 0) {
1580     return JVMTI_ERROR_NULL_POINTER;
1581   }
1582   for (int i = 0; i < count; i++) {
1583     jthread thread = list[i];
1584     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1585     if (thread_oop == nullptr || !thread_oop->is_a(vmClasses::BaseVirtualThread_klass())) {
1586       return JVMTI_ERROR_INVALID_THREAD;
1587     }
1588   }
1589   return JVMTI_ERROR_NONE;
1590 }
1591 
1592 bool
1593 JvmtiEnvBase::is_in_thread_list(jint count, const jthread* list, oop jt_oop) {
1594   for (int idx = 0; idx < count; idx++) {
1595     jthread thread = list[idx];
1596     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1597     if (thread_oop == jt_oop) {
1598       return true;
1599     }
1600   }
1601   return false;
1602 }
1603 
1604 class VM_SetNotifyJvmtiEventsMode : public VM_Operation {
1605 private:
1606   bool _enable;
1607 
1608   static void correct_jvmti_thread_state(JavaThread* jt) {
1609     oop  ct_oop = jt->threadObj();
1610     oop  vt_oop = jt->vthread();
1611     JvmtiThreadState* jt_state = jt->jvmti_thread_state();
1612     JvmtiThreadState* ct_state = java_lang_Thread::jvmti_thread_state(jt->threadObj());
1613     JvmtiThreadState* vt_state = vt_oop != nullptr ? java_lang_Thread::jvmti_thread_state(vt_oop) : nullptr;
1614     bool virt = vt_oop != nullptr && java_lang_VirtualThread::is_instance(vt_oop);
1615 
1616     // Correct jt->jvmti_thread_state() and jt->jvmti_vthread().
1617     // It was not maintained while notifyJvmti was disabled.
1618     if (virt) {
1619       jt->set_jvmti_thread_state(nullptr);  // reset jt->jvmti_thread_state()
1620       jt->set_jvmti_vthread(vt_oop);        // restore jt->jvmti_vthread()
1621     } else {
1622       jt->set_jvmti_thread_state(ct_state); // restore jt->jvmti_thread_state()
1623       jt->set_jvmti_vthread(ct_oop);        // restore jt->jvmti_vthread()
1624     }
1625   }
1626 
1627   // This function is called only if _enable == true.
1628   // Iterates over all JavaThread's, counts VTMS transitions and restores
1629   // jt->jvmti_thread_state() and jt->jvmti_vthread() for VTMS transition protocol.
1630   int count_transitions_and_correct_jvmti_thread_states() {
1631     int count = 0;
1632 
1633     for (JavaThread* jt : ThreadsListHandle()) {
1634       if (jt->is_in_VTMS_transition()) {
1635         count++;
1636         continue; // no need in JvmtiThreadState correction below if in transition
1637       }
1638       correct_jvmti_thread_state(jt);
1639     }
1640     return count;
1641   }
1642 
1643 public:
1644   VMOp_Type type() const { return VMOp_SetNotifyJvmtiEventsMode; }
1645   bool allow_nested_vm_operations() const { return false; }
1646   VM_SetNotifyJvmtiEventsMode(bool enable) : _enable(enable) {
1647   }
1648 
1649   void doit() {
1650     int count = _enable ? count_transitions_and_correct_jvmti_thread_states() : 0;
1651 
1652     JvmtiVTMSTransitionDisabler::set_VTMS_transition_count(count);
1653     JvmtiVTMSTransitionDisabler::set_VTMS_notify_jvmti_events(_enable);
1654   }
1655 };
1656 
1657 // This function is to support agents loaded into running VM.
1658 // Must be called in thread-in-native mode.
1659 bool
1660 JvmtiEnvBase::enable_virtual_threads_notify_jvmti() {
1661   if (!Continuations::enabled()) {
1662     return false;
1663   }
1664   if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
1665     return false; // already enabled
1666   }
1667   VM_SetNotifyJvmtiEventsMode op(true);
1668   VMThread::execute(&op);
1669   return true;
1670 }
1671 
1672 // This function is used in WhiteBox, only needed to test the function above.
1673 // It is unsafe to use this function when virtual threads are executed.
1674 // Must be called in thread-in-native mode.
1675 bool
1676 JvmtiEnvBase::disable_virtual_threads_notify_jvmti() {
1677   if (!Continuations::enabled()) {
1678     return false;
1679   }
1680   if (!JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
1681     return false; // already disabled
1682   }
1683   JvmtiVTMSTransitionDisabler disabler(true); // ensure there are no other disablers
1684   VM_SetNotifyJvmtiEventsMode op(false);
1685   VMThread::execute(&op);
1686   return true;
1687 }
1688 
1689 // java_thread - protected by ThreadsListHandle
1690 jvmtiError
1691 JvmtiEnvBase::suspend_thread(oop thread_oop, JavaThread* java_thread, bool single_suspend,
1692                              int* need_safepoint_p) {
1693   JavaThread* current = JavaThread::current();
1694   HandleMark hm(current);
1695   Handle thread_h(current, thread_oop);
1696   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1697 
1698   if (is_virtual) {
1699     if (single_suspend) {
1700       if (JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1701         return JVMTI_ERROR_THREAD_SUSPENDED;
1702       }
1703       JvmtiVTSuspender::register_vthread_suspend(thread_h());
1704       // Check if virtual thread is mounted and there is a java_thread.
1705       // A non-null java_thread is always passed in the !single_suspend case.
1706       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1707       java_thread = carrier_thread == nullptr ? nullptr : java_lang_Thread::thread(carrier_thread);
1708     }
1709     // The java_thread can be still blocked in VTMS transition after a previous JVMTI resume call.
1710     // There is no need to suspend the java_thread in this case. After vthread unblocking,
1711     // it will check for ext_suspend request and suspend itself if necessary.
1712     if (java_thread == nullptr || java_thread->is_suspended()) {
1713       // We are done if the virtual thread is unmounted or
1714       // the java_thread is externally suspended.
1715       return JVMTI_ERROR_NONE;
1716     }
1717     // The virtual thread is mounted: suspend the java_thread.
1718   }
1719   // Don't allow hidden thread suspend request.
1720   if (java_thread->is_hidden_from_external_view()) {
1721     return JVMTI_ERROR_NONE;
1722   }
1723   bool is_thread_carrying = is_thread_carrying_vthread(java_thread, thread_h());
1724 
1725   // A case of non-virtual thread.
1726   if (!is_virtual) {
1727     // Thread.suspend() is used in some tests. It sets jt->is_suspended() only.
1728     if (java_thread->is_carrier_thread_suspended() ||
1729         (!is_thread_carrying && java_thread->is_suspended())) {
1730       return JVMTI_ERROR_THREAD_SUSPENDED;
1731     }
1732     java_thread->set_carrier_thread_suspended();
1733   }
1734   assert(!java_thread->is_in_VTMS_transition(), "sanity check");
1735 
1736   assert(!single_suspend || (!is_virtual && java_thread->is_carrier_thread_suspended()) ||
1737           (is_virtual && JvmtiVTSuspender::is_vthread_suspended(thread_h())),
1738          "sanity check");
1739 
1740   // An attempt to handshake-suspend a thread carrying a virtual thread will result in
1741   // suspension of mounted virtual thread. So, we just mark it as suspended
1742   // and it will be actually suspended at virtual thread unmount transition.
1743   if (!is_thread_carrying) {
1744     assert(thread_h() != nullptr, "sanity check");
1745     assert(single_suspend || thread_h()->is_a(vmClasses::BaseVirtualThread_klass()),
1746            "SuspendAllVirtualThreads should never suspend non-virtual threads");
1747     // Case of mounted virtual or attached carrier thread.
1748     if (!JvmtiSuspendControl::suspend(java_thread)) {
1749       // Thread is already suspended or in process of exiting.
1750       if (java_thread->is_exiting()) {
1751         // The thread was in the process of exiting.
1752         return JVMTI_ERROR_THREAD_NOT_ALIVE;
1753       }
1754       return JVMTI_ERROR_THREAD_SUSPENDED;
1755     }
1756   }
1757   return JVMTI_ERROR_NONE;
1758 }
1759 
1760 // java_thread - protected by ThreadsListHandle
1761 jvmtiError
1762 JvmtiEnvBase::resume_thread(oop thread_oop, JavaThread* java_thread, bool single_resume) {
1763   JavaThread* current = JavaThread::current();
1764   HandleMark hm(current);
1765   Handle thread_h(current, thread_oop);
1766   bool is_virtual = java_lang_VirtualThread::is_instance(thread_h());
1767 
1768   if (is_virtual) {
1769     if (single_resume) {
1770       if (!JvmtiVTSuspender::is_vthread_suspended(thread_h())) {
1771         return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1772       }
1773       JvmtiVTSuspender::register_vthread_resume(thread_h());
1774       // Check if virtual thread is mounted and there is a java_thread.
1775       // A non-null java_thread is always passed in the !single_resume case.
1776       oop carrier_thread = java_lang_VirtualThread::carrier_thread(thread_h());
1777       java_thread = carrier_thread == nullptr ? nullptr : java_lang_Thread::thread(carrier_thread);
1778     }
1779     // The java_thread can be still blocked in VTMS transition after a previous JVMTI suspend call.
1780     // There is no need to resume the java_thread in this case. After vthread unblocking,
1781     // it will check for is_vthread_suspended request and remain resumed if necessary.
1782     if (java_thread == nullptr || !java_thread->is_suspended()) {
1783       // We are done if the virtual thread is unmounted or
1784       // the java_thread is not externally suspended.
1785       return JVMTI_ERROR_NONE;
1786     }
1787     // The virtual thread is mounted and java_thread is supended: resume the java_thread.
1788   }
1789   // Don't allow hidden thread resume request.
1790   if (java_thread->is_hidden_from_external_view()) {
1791     return JVMTI_ERROR_NONE;
1792   }
1793   bool is_thread_carrying = is_thread_carrying_vthread(java_thread, thread_h());
1794 
1795   // A case of a non-virtual thread.
1796   if (!is_virtual) {
1797     if (!java_thread->is_carrier_thread_suspended() &&
1798         (is_thread_carrying || !java_thread->is_suspended())) {
1799       return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1800     }
1801     java_thread->clear_carrier_thread_suspended();
1802   }
1803   assert(!java_thread->is_in_VTMS_transition(), "sanity check");
1804 
1805   if (!is_thread_carrying) {
1806     assert(thread_h() != nullptr, "sanity check");
1807     assert(single_resume || thread_h()->is_a(vmClasses::BaseVirtualThread_klass()),
1808            "ResumeAllVirtualThreads should never resume non-virtual threads");
1809     if (java_thread->is_suspended()) {
1810       if (!JvmtiSuspendControl::resume(java_thread)) {
1811         return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1812       }
1813     }
1814   }
1815   return JVMTI_ERROR_NONE;
1816 }
1817 
1818 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1819   _env = env;
1820   _allocations = new (mtServiceability) GrowableArray<unsigned char*>(20, mtServiceability);
1821   _failed = false;
1822 }
1823 ResourceTracker::~ResourceTracker() {
1824   if (_failed) {
1825     for (int i=0; i<_allocations->length(); i++) {
1826       _env->deallocate(_allocations->at(i));
1827     }
1828   }
1829   delete _allocations;
1830 }
1831 
1832 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1833   unsigned char *ptr;
1834   jvmtiError err = _env->allocate(size, &ptr);
1835   if (err == JVMTI_ERROR_NONE) {
1836     _allocations->append(ptr);
1837     *mem_ptr = ptr;
1838   } else {
1839     *mem_ptr = nullptr;
1840     _failed = true;
1841   }
1842   return err;
1843  }
1844 
1845 unsigned char* ResourceTracker::allocate(jlong size) {
1846   unsigned char* ptr;
1847   allocate(size, &ptr);
1848   return ptr;
1849 }
1850 
1851 char* ResourceTracker::strdup(const char* str) {
1852   char *dup_str = (char*)allocate(strlen(str)+1);
1853   if (dup_str != nullptr) {
1854     strcpy(dup_str, str);
1855   }
1856   return dup_str;
1857 }
1858 
1859 struct StackInfoNode {
1860   struct StackInfoNode *next;
1861   jvmtiStackInfo info;
1862 };
1863 
1864 // Create a jvmtiStackInfo inside a linked list node and create a
1865 // buffer for the frame information, both allocated as resource objects.
1866 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1867 // Note that either or both of thr and thread_oop
1868 // may be null if the thread is new or has exited.
1869 void
1870 MultipleStackTracesCollector::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1871 #ifdef ASSERT
1872   Thread *current_thread = Thread::current();
1873   assert(SafepointSynchronize::is_at_safepoint() ||
1874          thr == nullptr ||
1875          thr->is_handshake_safe_for(current_thread),
1876          "unmounted virtual thread / call by myself / at safepoint / at handshake");
1877 #endif
1878 
1879   jint state = 0;
1880   struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
1881   jvmtiStackInfo *infop = &(node->info);
1882 
1883   node->next = head();
1884   set_head(node);
1885   infop->frame_count = 0;
1886   infop->frame_buffer = nullptr;
1887   infop->thread = jt;
1888 
1889   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1890     state = JvmtiEnvBase::get_vthread_state(thread_oop, thr);
1891 
1892     if ((state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1893       javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(thread_oop);
1894       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1895       _result = env()->get_stack_trace(jvf, 0, max_frame_count(),
1896                                        infop->frame_buffer, &(infop->frame_count));
1897     }
1898   } else {
1899     state = JvmtiEnvBase::get_thread_state(thread_oop, thr);
1900     if (thr != nullptr && (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1901       infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1902       _result = env()->get_stack_trace(thr, 0, max_frame_count(),
1903                                        infop->frame_buffer, &(infop->frame_count));
1904     }
1905   }
1906   _frame_count_total += infop->frame_count;
1907   infop->state = state;
1908 }
1909 
1910 // Based on the stack information in the linked list, allocate memory
1911 // block to return and fill it from the info in the linked list.
1912 void
1913 MultipleStackTracesCollector::allocate_and_fill_stacks(jint thread_count) {
1914   // do I need to worry about alignment issues?
1915   jlong alloc_size =  thread_count       * sizeof(jvmtiStackInfo)
1916                     + _frame_count_total * sizeof(jvmtiFrameInfo);
1917   env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1918 
1919   // pointers to move through the newly allocated space as it is filled in
1920   jvmtiStackInfo *si = _stack_info + thread_count;      // bottom of stack info
1921   jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si;            // is the top of frame info
1922 
1923   // copy information in resource area into allocated buffer
1924   // insert stack info backwards since linked list is backwards
1925   // insert frame info forwards
1926   // walk the StackInfoNodes
1927   for (struct StackInfoNode *sin = head(); sin != nullptr; sin = sin->next) {
1928     jint frame_count = sin->info.frame_count;
1929     size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
1930     --si;
1931     memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
1932     if (frames_size == 0) {
1933       si->frame_buffer = nullptr;
1934     } else {
1935       memcpy(fi, sin->info.frame_buffer, frames_size);
1936       si->frame_buffer = fi;  // point to the new allocated copy of the frames
1937       fi += frame_count;
1938     }
1939   }
1940   assert(si == _stack_info, "the last copied stack info must be the first record");
1941   assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1942          "the last copied frame info must be the last record");
1943 }
1944 
1945 
1946 void
1947 VM_GetThreadListStackTraces::doit() {
1948   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1949 
1950   ResourceMark rm;
1951   ThreadsListHandle tlh;
1952   for (int i = 0; i < _thread_count; ++i) {
1953     jthread jt = _thread_list[i];
1954     JavaThread* java_thread = nullptr;
1955     oop thread_oop = nullptr;
1956     jvmtiError err = JvmtiEnvBase::get_threadOop_and_JavaThread(tlh.list(), jt, nullptr, &java_thread, &thread_oop);
1957 
1958     if (err != JVMTI_ERROR_NONE) {
1959       // We got an error code so we don't have a JavaThread *, but
1960       // only return an error from here if we didn't get a valid
1961       // thread_oop.
1962       // In the virtual thread case the get_threadOop_and_JavaThread is expected to correctly set
1963       // the thread_oop and return JVMTI_ERROR_THREAD_NOT_ALIVE which we ignore here.
1964       // The corresponding thread state will be recorded in the jvmtiStackInfo.state.
1965       if (thread_oop == nullptr) {
1966         _collector.set_result(err);
1967         return;
1968       }
1969       // We have a valid thread_oop.
1970     }
1971     _collector.fill_frames(jt, java_thread, thread_oop);
1972   }
1973   _collector.allocate_and_fill_stacks(_thread_count);
1974 }
1975 
1976 void
1977 GetSingleStackTraceClosure::do_thread(Thread *target) {
1978   JavaThread *jt = JavaThread::cast(target);
1979   oop thread_oop = JNIHandles::resolve_external_guard(_jthread);
1980 
1981   if (!jt->is_exiting() && thread_oop != nullptr) {
1982     ResourceMark rm;
1983     _collector.fill_frames(_jthread, jt, thread_oop);
1984     _collector.allocate_and_fill_stacks(1);
1985   }
1986 }
1987 
1988 void
1989 VM_GetAllStackTraces::doit() {
1990   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1991 
1992   ResourceMark rm;
1993   _final_thread_count = 0;
1994   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1995     oop thread_oop = jt->threadObj();
1996     if (thread_oop != nullptr &&
1997         !jt->is_exiting() &&
1998         java_lang_Thread::is_alive(thread_oop) &&
1999         !jt->is_hidden_from_external_view() &&
2000         !thread_oop->is_a(vmClasses::BoundVirtualThread_klass())) {
2001       ++_final_thread_count;
2002       // Handle block of the calling thread is used to create local refs.
2003       _collector.fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
2004                              jt, thread_oop);
2005     }
2006   }
2007   _collector.allocate_and_fill_stacks(_final_thread_count);
2008 }
2009 
2010 // Verifies that the top frame is a java frame in an expected state.
2011 // Deoptimizes frame if needed.
2012 // Checks that the frame method signature matches the return type (tos).
2013 // HandleMark must be defined in the caller only.
2014 // It is to keep a ret_ob_h handle alive after return to the caller.
2015 jvmtiError
2016 JvmtiEnvBase::check_top_frame(Thread* current_thread, JavaThread* java_thread,
2017                               jvalue value, TosState tos, Handle* ret_ob_h) {
2018   ResourceMark rm(current_thread);
2019 
2020   javaVFrame* jvf = jvf_for_thread_and_depth(java_thread, 0);
2021   NULL_CHECK(jvf, JVMTI_ERROR_NO_MORE_FRAMES);
2022 
2023   if (jvf->method()->is_native()) {
2024     return JVMTI_ERROR_OPAQUE_FRAME;
2025   }
2026 
2027   // If the frame is a compiled one, need to deoptimize it.
2028   if (jvf->is_compiled_frame()) {
2029     if (!jvf->fr().can_be_deoptimized()) {
2030       return JVMTI_ERROR_OPAQUE_FRAME;
2031     }
2032     Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());
2033   }
2034 
2035   // Get information about method return type
2036   Symbol* signature = jvf->method()->signature();
2037 
2038   ResultTypeFinder rtf(signature);
2039   TosState fr_tos = as_TosState(rtf.type());
2040   if (fr_tos != tos) {
2041     if (tos != itos || (fr_tos != btos && fr_tos != ztos && fr_tos != ctos && fr_tos != stos)) {
2042       return JVMTI_ERROR_TYPE_MISMATCH;
2043     }
2044   }
2045 
2046   // Check that the jobject class matches the return type signature.
2047   jobject jobj = value.l;
2048   if (tos == atos && jobj != nullptr) { // null reference is allowed
2049     Handle ob_h(current_thread, JNIHandles::resolve_external_guard(jobj));
2050     NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
2051     Klass* ob_k = ob_h()->klass();
2052     NULL_CHECK(ob_k, JVMTI_ERROR_INVALID_OBJECT);
2053 
2054     // Method return type signature.
2055     char* ty_sign = 1 + strchr(signature->as_C_string(), JVM_SIGNATURE_ENDFUNC);
2056 
2057     if (!VM_GetOrSetLocal::is_assignable(ty_sign, ob_k, current_thread)) {
2058       return JVMTI_ERROR_TYPE_MISMATCH;
2059     }
2060     *ret_ob_h = ob_h;
2061   }
2062   return JVMTI_ERROR_NONE;
2063 } /* end check_top_frame */
2064 
2065 
2066 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
2067 // Main difference is on the last stage in the interpreter.
2068 // The PopFrame stops method execution to continue execution
2069 // from the same method call instruction.
2070 // The ForceEarlyReturn forces return from method so the execution
2071 // continues at the bytecode following the method call.
2072 
2073 // thread - NOT protected by ThreadsListHandle and NOT pre-checked
2074 
2075 jvmtiError
2076 JvmtiEnvBase::force_early_return(jthread thread, jvalue value, TosState tos) {
2077   JavaThread* current_thread = JavaThread::current();
2078   HandleMark hm(current_thread);
2079 
2080   JvmtiVTMSTransitionDisabler disabler(thread);
2081   ThreadsListHandle tlh(current_thread);
2082 
2083   JavaThread* java_thread = nullptr;
2084   oop thread_obj = nullptr;
2085   jvmtiError err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
2086 
2087   if (err != JVMTI_ERROR_NONE) {
2088     return err;
2089   }
2090   bool self = java_thread == current_thread;
2091 
2092   err = check_non_suspended_or_opaque_frame(java_thread, thread_obj, self);
2093   if (err != JVMTI_ERROR_NONE) {
2094     return err;
2095   }
2096 
2097   // retrieve or create the state
2098   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
2099   if (state == nullptr) {
2100     return JVMTI_ERROR_THREAD_NOT_ALIVE;
2101   }
2102 
2103   // Eagerly reallocate scalar replaced objects.
2104   EscapeBarrier eb(true, current_thread, java_thread);
2105   if (!eb.deoptimize_objects(0)) {
2106     // Reallocation of scalar replaced objects failed -> return with error
2107     return JVMTI_ERROR_OUT_OF_MEMORY;
2108   }
2109 
2110   SetForceEarlyReturn op(state, value, tos);
2111   if (self) {
2112     op.doit(java_thread, self);
2113   } else {
2114     Handshake::execute(&op, java_thread);
2115   }
2116   return op.result();
2117 }
2118 
2119 void
2120 SetForceEarlyReturn::doit(Thread *target, bool self) {
2121   JavaThread* java_thread = JavaThread::cast(target);
2122   Thread* current_thread = Thread::current();
2123   HandleMark   hm(current_thread);
2124 
2125   if (java_thread->is_exiting()) {
2126     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2127   }
2128 
2129   // Check to see if a ForceEarlyReturn was already in progress
2130   if (_state->is_earlyret_pending()) {
2131     // Probably possible for JVMTI clients to trigger this, but the
2132     // JPDA backend shouldn't allow this to happen
2133     _result = JVMTI_ERROR_INTERNAL;
2134     return;
2135   }
2136   {
2137     // The same as for PopFrame. Workaround bug:
2138     //  4812902: popFrame hangs if the method is waiting at a synchronize
2139     // Catch this condition and return an error to avoid hanging.
2140     // Now JVMTI spec allows an implementation to bail out with an opaque
2141     // frame error.
2142     OSThread* osThread = java_thread->osthread();
2143     if (osThread->get_state() == MONITOR_WAIT) {
2144       _result = JVMTI_ERROR_OPAQUE_FRAME;
2145       return;
2146     }
2147   }
2148 
2149   Handle ret_ob_h;
2150   _result = JvmtiEnvBase::check_top_frame(current_thread, java_thread, _value, _tos, &ret_ob_h);
2151   if (_result != JVMTI_ERROR_NONE) {
2152     return;
2153   }
2154   assert(_tos != atos || _value.l == nullptr || ret_ob_h() != nullptr,
2155          "return object oop must not be null if jobject is not null");
2156 
2157   // Update the thread state to reflect that the top frame must be
2158   // forced to return.
2159   // The current frame will be returned later when the suspended
2160   // thread is resumed and right before returning from VM to Java.
2161   // (see call_VM_base() in assembler_<cpu>.cpp).
2162 
2163   _state->set_earlyret_pending();
2164   _state->set_earlyret_oop(ret_ob_h());
2165   _state->set_earlyret_value(_value, _tos);
2166 
2167   // Set pending step flag for this early return.
2168   // It is cleared when next step event is posted.
2169   _state->set_pending_step_for_earlyret();
2170 }
2171 
2172 void
2173 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
2174   if ( _error != JVMTI_ERROR_NONE) {
2175     // Error occurred in previous iteration so no need to add
2176     // to the list.
2177     return;
2178   }
2179   // Filter out on stack monitors collected during stack walk.
2180   oop obj = mon->object();
2181   bool found = false;
2182   for (int j = 0; j < _owned_monitors_list->length(); j++) {
2183     jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
2184     oop check = JNIHandles::resolve(jobj);
2185     if (check == obj) {
2186       // On stack monitor already collected during the stack walk.
2187       found = true;
2188       break;
2189     }
2190   }
2191   if (found == false) {
2192     // This is off stack monitor (e.g. acquired via jni MonitorEnter).
2193     jvmtiError err;
2194     jvmtiMonitorStackDepthInfo *jmsdi;
2195     err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
2196     if (err != JVMTI_ERROR_NONE) {
2197       _error = err;
2198       return;
2199     }
2200     Handle hobj(Thread::current(), obj);
2201     jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
2202     // stack depth is unknown for this monitor.
2203     jmsdi->stack_depth = -1;
2204     _owned_monitors_list->append(jmsdi);
2205   }
2206 }
2207 
2208 GrowableArray<OopHandle>* JvmtiModuleClosure::_tbl = nullptr;
2209 
2210 void JvmtiModuleClosure::do_module(ModuleEntry* entry) {
2211   assert_locked_or_safepoint(Module_lock);
2212   OopHandle module = entry->module_handle();
2213   guarantee(module.resolve() != nullptr, "module object is null");
2214   _tbl->push(module);
2215 }
2216 
2217 jvmtiError
2218 JvmtiModuleClosure::get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr) {
2219   ResourceMark rm;
2220   MutexLocker mcld(ClassLoaderDataGraph_lock);
2221   MutexLocker ml(Module_lock);
2222 
2223   _tbl = new GrowableArray<OopHandle>(77);
2224   if (_tbl == nullptr) {
2225     return JVMTI_ERROR_OUT_OF_MEMORY;
2226   }
2227 
2228   // Iterate over all the modules loaded to the system.
2229   ClassLoaderDataGraph::modules_do(&do_module);
2230 
2231   jint len = _tbl->length();
2232   guarantee(len > 0, "at least one module must be present");
2233 
2234   jobject* array = (jobject*)env->jvmtiMalloc((jlong)(len * sizeof(jobject)));
2235   if (array == nullptr) {
2236     return JVMTI_ERROR_OUT_OF_MEMORY;
2237   }
2238   for (jint idx = 0; idx < len; idx++) {
2239     array[idx] = JNIHandles::make_local(_tbl->at(idx).resolve());
2240   }
2241   _tbl = nullptr;
2242   *modules_ptr = array;
2243   *module_count_ptr = len;
2244   return JVMTI_ERROR_NONE;
2245 }
2246 
2247 void
2248 UpdateForPopTopFrameClosure::doit(Thread *target, bool self) {
2249   Thread* current_thread  = Thread::current();
2250   HandleMark hm(current_thread);
2251   JavaThread* java_thread = JavaThread::cast(target);
2252 
2253   if (java_thread->is_exiting()) {
2254     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2255   }
2256   assert(java_thread == _state->get_thread(), "Must be");
2257 
2258   // Check to see if a PopFrame was already in progress
2259   if (java_thread->popframe_condition() != JavaThread::popframe_inactive) {
2260     // Probably possible for JVMTI clients to trigger this, but the
2261     // JPDA backend shouldn't allow this to happen
2262     _result = JVMTI_ERROR_INTERNAL;
2263     return;
2264   }
2265 
2266   // Was workaround bug
2267   //    4812902: popFrame hangs if the method is waiting at a synchronize
2268   // Catch this condition and return an error to avoid hanging.
2269   // Now JVMTI spec allows an implementation to bail out with an opaque frame error.
2270   OSThread* osThread = java_thread->osthread();
2271   if (osThread->get_state() == MONITOR_WAIT) {
2272     _result = JVMTI_ERROR_OPAQUE_FRAME;
2273     return;
2274   }
2275 
2276   ResourceMark rm(current_thread);
2277   // Check if there is more than one Java frame in this thread, that the top two frames
2278   // are Java (not native) frames, and that there is no intervening VM frame
2279   int frame_count = 0;
2280   bool is_interpreted[2];
2281   intptr_t *frame_sp[2];
2282   // The 2-nd arg of constructor is needed to stop iterating at java entry frame.
2283   for (vframeStream vfs(java_thread, true, false /* process_frames */); !vfs.at_end(); vfs.next()) {
2284     methodHandle mh(current_thread, vfs.method());
2285     if (mh->is_native()) {
2286       _result = JVMTI_ERROR_OPAQUE_FRAME;
2287       return;
2288     }
2289     is_interpreted[frame_count] = vfs.is_interpreted_frame();
2290     frame_sp[frame_count] = vfs.frame_id();
2291     if (++frame_count > 1) break;
2292   }
2293   if (frame_count < 2)  {
2294     // We haven't found two adjacent non-native Java frames on the top.
2295     // There can be two situations here:
2296     //  1. There are no more java frames
2297     //  2. Two top java frames are separated by non-java native frames
2298     if (JvmtiEnvBase::jvf_for_thread_and_depth(java_thread, 1) == nullptr) {
2299       _result = JVMTI_ERROR_NO_MORE_FRAMES;
2300       return;
2301     } else {
2302       // Intervening non-java native or VM frames separate java frames.
2303       // Current implementation does not support this. See bug #5031735.
2304       // In theory it is possible to pop frames in such cases.
2305       _result = JVMTI_ERROR_OPAQUE_FRAME;
2306       return;
2307     }
2308   }
2309 
2310   // If any of the top 2 frames is a compiled one, need to deoptimize it
2311   for (int i = 0; i < 2; i++) {
2312     if (!is_interpreted[i]) {
2313       Deoptimization::deoptimize_frame(java_thread, frame_sp[i]);
2314     }
2315   }
2316 
2317   // Update the thread state to reflect that the top frame is popped
2318   // so that cur_stack_depth is maintained properly and all frameIDs
2319   // are invalidated.
2320   // The current frame will be popped later when the suspended thread
2321   // is resumed and right before returning from VM to Java.
2322   // (see call_VM_base() in assembler_<cpu>.cpp).
2323 
2324   // It's fine to update the thread state here because no JVMTI events
2325   // shall be posted for this PopFrame.
2326 
2327   _state->update_for_pop_top_frame();
2328   java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
2329   // Set pending step flag for this popframe and it is cleared when next
2330   // step event is posted.
2331   _state->set_pending_step_for_popframe();
2332   _result = JVMTI_ERROR_NONE;
2333 }
2334 
2335 void
2336 SetFramePopClosure::doit(Thread *target, bool self) {
2337   ResourceMark rm;
2338   JavaThread* java_thread = JavaThread::cast(target);
2339 
2340   if (java_thread->is_exiting()) {
2341     return; /* JVMTI_ERROR_THREAD_NOT_ALIVE (default) */
2342   }
2343   assert(_state->get_thread_or_saved() == java_thread, "Must be");
2344 
2345   if (!self && !java_thread->is_suspended()) {
2346     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2347     return;
2348   }
2349   if (!java_thread->has_last_Java_frame()) {
2350     _result = JVMTI_ERROR_NO_MORE_FRAMES;
2351     return;
2352   }
2353   RegisterMap reg_map(java_thread,
2354                       RegisterMap::UpdateMap::include,
2355                       RegisterMap::ProcessFrames::skip,
2356                       RegisterMap::WalkContinuation::include);
2357   javaVFrame* jvf = JvmtiEnvBase::get_cthread_last_java_vframe(java_thread, &reg_map);
2358   _result = ((JvmtiEnvBase*)_env)->set_frame_pop(_state, jvf, _depth);
2359 }
2360 
2361 void
2362 GetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2363   JavaThread *jt = JavaThread::cast(target);
2364   if (!jt->is_exiting() && (jt->threadObj() != nullptr)) {
2365     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread,
2366                                                          jt,
2367                                                          _owned_monitors_list);
2368   }
2369 }
2370 
2371 void
2372 GetCurrentContendedMonitorClosure::do_thread(Thread *target) {
2373   JavaThread *jt = JavaThread::cast(target);
2374   if (!jt->is_exiting() && (jt->threadObj() != nullptr)) {
2375     _result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor(_calling_thread,
2376                                                                     jt,
2377                                                                     _owned_monitor_ptr,
2378                                                                     _is_virtual);
2379   }
2380 }
2381 
2382 void
2383 VM_VirtualThreadGetStackTrace::doit() {
2384   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2385     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2386     return;
2387   }
2388   ResourceMark rm;
2389   javaVFrame* jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2390 
2391   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2392                                                     _start_depth, _max_count,
2393                                                     _frame_buffer, _count_ptr);
2394 }
2395 
2396 void
2397 GetStackTraceClosure::do_thread(Thread *target) {
2398   JavaThread *jt = JavaThread::cast(target);
2399   if (!jt->is_exiting() && jt->threadObj() != nullptr) {
2400     _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jt,
2401                                                       _start_depth, _max_count,
2402                                                       _frame_buffer, _count_ptr);
2403   }
2404 }
2405 
2406 #ifdef ASSERT
2407 void
2408 PrintStackTraceClosure::do_thread_impl(Thread *target) {
2409   JavaThread *java_thread = JavaThread::cast(target);
2410   Thread *current_thread = Thread::current();
2411 
2412   ResourceMark rm (current_thread);
2413   const char* tname = JvmtiTrace::safe_get_thread_name(java_thread);
2414   oop t_oop = java_thread->jvmti_vthread();
2415   t_oop = t_oop == nullptr ? java_thread->threadObj() : t_oop;
2416   bool is_vt_suspended = java_lang_VirtualThread::is_instance(t_oop) && JvmtiVTSuspender::is_vthread_suspended(t_oop);
2417 
2418   log_error(jvmti)("%s(%s) exiting: %d is_susp: %d is_thread_susp: %d is_vthread_susp: %d "
2419                    "is_VTMS_transition_disabler: %d, is_in_VTMS_transition = %d\n",
2420                    tname, java_thread->name(), java_thread->is_exiting(),
2421                    java_thread->is_suspended(), java_thread->is_carrier_thread_suspended(), is_vt_suspended,
2422                    java_thread->is_VTMS_transition_disabler(), java_thread->is_in_VTMS_transition());
2423 
2424   if (java_thread->has_last_Java_frame()) {
2425     RegisterMap reg_map(java_thread,
2426                         RegisterMap::UpdateMap::include,
2427                         RegisterMap::ProcessFrames::include,
2428                         RegisterMap::WalkContinuation::skip);
2429     ResourceMark rm(current_thread);
2430     HandleMark hm(current_thread);
2431     javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
2432     while (jvf != nullptr) {
2433       log_error(jvmti)("  %s:%d",
2434                        jvf->method()->external_name(),
2435                        jvf->method()->line_number_from_bci(jvf->bci()));
2436       jvf = jvf->java_sender();
2437     }
2438   }
2439   log_error(jvmti)("\n");
2440 }
2441 
2442 void
2443 PrintStackTraceClosure::do_thread(Thread *target) {
2444   JavaThread *java_thread = JavaThread::cast(target);
2445   Thread *current_thread = Thread::current();
2446 
2447   assert(SafepointSynchronize::is_at_safepoint() ||
2448          java_thread->is_handshake_safe_for(current_thread),
2449          "call by myself / at safepoint / at handshake");
2450 
2451   PrintStackTraceClosure::do_thread_impl(target);
2452 }
2453 #endif
2454 
2455 void
2456 VM_VirtualThreadGetFrameCount::doit() {
2457   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2458 }
2459 
2460 void
2461 GetFrameCountClosure::do_thread(Thread *target) {
2462   JavaThread* jt = JavaThread::cast(target);
2463   assert(target == jt, "just checking");
2464   if (!jt->is_exiting() && jt->threadObj() != nullptr) {
2465     _result = ((JvmtiEnvBase*)_env)->get_frame_count(jt, _count_ptr);
2466   }
2467 }
2468 
2469 void
2470 GetFrameLocationClosure::do_thread(Thread *target) {
2471   JavaThread *jt = JavaThread::cast(target);
2472   if (!jt->is_exiting() && jt->threadObj() != nullptr) {
2473     _result = ((JvmtiEnvBase*)_env)->get_frame_location(jt, _depth,
2474                                                         _method_ptr, _location_ptr);
2475   }
2476 }
2477 
2478 void
2479 VirtualThreadGetOwnedMonitorInfoClosure::do_thread(Thread *target) {
2480   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2481     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2482     return;
2483   }
2484   JavaThread* java_thread = JavaThread::cast(target);
2485   Thread* cur_thread = Thread::current();
2486   ResourceMark rm(cur_thread);
2487   HandleMark hm(cur_thread);
2488 
2489   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2490 
2491   if (!java_thread->is_exiting() && java_thread->threadObj() != nullptr) {
2492     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(java_thread,
2493                                                          java_thread,
2494                                                          jvf,
2495                                                          _owned_monitors_list);
2496   }
2497 }
2498 
2499 void
2500 VirtualThreadGetThreadClosure::do_thread(Thread *target) {
2501   assert(target->is_Java_thread(), "just checking");
2502   JavaThread *jt = JavaThread::cast(target);
2503   oop carrier_thread = java_lang_VirtualThread::carrier_thread(_vthread_h());
2504   *_carrier_thread_ptr = (jthread)JNIHandles::make_local(jt, carrier_thread);
2505 }
2506 
2507 void
2508 VirtualThreadGetStackTraceClosure::do_thread(Thread *target) {
2509   assert(target->is_Java_thread(), "just checking");
2510   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2511     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2512     return;
2513   }
2514   Thread* cur_thread = Thread::current();
2515   ResourceMark rm(cur_thread);
2516   HandleMark hm(cur_thread);
2517 
2518   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2519   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
2520                                                     _start_depth, _max_count,
2521                                                     _frame_buffer, _count_ptr);
2522 }
2523 
2524 void
2525 VirtualThreadGetFrameCountClosure::do_thread(Thread *target) {
2526   assert(target->is_Java_thread(), "just checking");
2527   _result = ((JvmtiEnvBase*)_env)->get_frame_count(_vthread_h(), _count_ptr);
2528 }
2529 
2530 void
2531 VirtualThreadGetFrameLocationClosure::do_thread(Thread *target) {
2532   assert(target->is_Java_thread(), "just checking");
2533   _result = ((JvmtiEnvBase*)_env)->get_frame_location(_vthread_h(), _depth,
2534                                                       _method_ptr, _location_ptr);
2535 }
2536 
2537 void
2538 VirtualThreadGetThreadStateClosure::do_thread(Thread *target) {
2539   assert(target->is_Java_thread(), "just checking");
2540   jshort vthread_state = java_lang_VirtualThread::state(_vthread_h());
2541   oop carrier_thread_oop = java_lang_VirtualThread::carrier_thread(_vthread_h());
2542   jint state;
2543 
2544   if (vthread_state == java_lang_VirtualThread::RUNNING && carrier_thread_oop != nullptr) {
2545     state = (jint) java_lang_Thread::get_thread_status(carrier_thread_oop);
2546     JavaThread* java_thread = java_lang_Thread::thread(carrier_thread_oop);
2547     if (java_thread->is_suspended()) {
2548       state |= JVMTI_THREAD_STATE_SUSPENDED;
2549     }
2550   } else {
2551     state = (jint) java_lang_VirtualThread::map_state_to_thread_status(vthread_state);
2552   }
2553   if (java_lang_Thread::interrupted(_vthread_h())) {
2554     state |= JVMTI_THREAD_STATE_INTERRUPTED;
2555   }
2556   *_state_ptr = state;
2557   _result = JVMTI_ERROR_NONE;
2558 }
2559 
2560 void
2561 VirtualThreadSetFramePopClosure::doit(Thread *target, bool self) {
2562   if (!JvmtiEnvBase::is_vthread_alive(_vthread_h())) {
2563     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
2564     return;
2565   }
2566   if (!self && !JvmtiVTSuspender::is_vthread_suspended(_vthread_h())) {
2567     _result = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
2568     return;
2569   }
2570   ResourceMark rm;
2571   javaVFrame *jvf = JvmtiEnvBase::get_vthread_jvf(_vthread_h());
2572   _result = ((JvmtiEnvBase*)_env)->set_frame_pop(_state, jvf, _depth);
2573 }