1 /*
   2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoaderExt.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/modules.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmClasses.hpp"
  32 #include "classfile/vmSymbols.hpp"
  33 #include "gc/shared/collectedHeap.hpp"
  34 #include "interpreter/bytecodeStream.hpp"
  35 #include "interpreter/interpreter.hpp"
  36 #include "jfr/jfrEvents.hpp"
  37 #include "jvmtifiles/jvmtiEnv.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logConfiguration.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "memory/universe.hpp"
  42 #include "oops/instanceKlass.hpp"
  43 #include "oops/klass.inline.hpp"
  44 #include "oops/objArrayOop.inline.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "prims/jniCheck.hpp"
  47 #include "prims/jvm_misc.hpp"
  48 #include "prims/jvmtiAgentThread.hpp"
  49 #include "prims/jvmtiClassFileReconstituter.hpp"
  50 #include "prims/jvmtiCodeBlobEvents.hpp"
  51 #include "prims/jvmtiExtensions.hpp"
  52 #include "prims/jvmtiGetLoadedClasses.hpp"
  53 #include "prims/jvmtiImpl.hpp"
  54 #include "prims/jvmtiManageCapabilities.hpp"
  55 #include "prims/jvmtiRawMonitor.hpp"
  56 #include "prims/jvmtiRedefineClasses.hpp"
  57 #include "prims/jvmtiTagMap.hpp"
  58 #include "prims/jvmtiThreadState.inline.hpp"
  59 #include "prims/jvmtiUtil.hpp"
  60 #include "runtime/arguments.hpp"
  61 #include "runtime/deoptimization.hpp"
  62 #include "runtime/fieldDescriptor.inline.hpp"
  63 #include "runtime/handles.inline.hpp"
  64 #include "runtime/interfaceSupport.inline.hpp"
  65 #include "runtime/javaCalls.hpp"
  66 #include "runtime/jfieldIDWorkaround.hpp"
  67 #include "runtime/jniHandles.inline.hpp"
  68 #include "runtime/objectMonitor.inline.hpp"
  69 #include "runtime/os.hpp"
  70 #include "runtime/osThread.hpp"
  71 #include "runtime/reflectionUtils.hpp"
  72 #include "runtime/signature.hpp"
  73 #include "runtime/thread.inline.hpp"
  74 #include "runtime/threadHeapSampler.hpp"
  75 #include "runtime/threadSMR.hpp"
  76 #include "runtime/timerTrace.hpp"
  77 #include "runtime/vframe.inline.hpp"
  78 #include "runtime/vmThread.hpp"
  79 #include "services/threadService.hpp"
  80 #include "utilities/exceptions.hpp"
  81 #include "utilities/preserveException.hpp"
  82 #include "utilities/utf8.hpp"
  83 
  84 
  85 #define FIXLATER 0 // REMOVE this when completed.
  86 
  87  // FIXLATER: hook into JvmtiTrace
  88 #define TraceJVMTICalls false
  89 
  90 JvmtiEnv::JvmtiEnv(jint version) : JvmtiEnvBase(version) {
  91 }
  92 
  93 JvmtiEnv::~JvmtiEnv() {
  94 }
  95 
  96 JvmtiEnv*
  97 JvmtiEnv::create_a_jvmti(jint version) {
  98   return new JvmtiEnv(version);
  99 }
 100 
 101 // VM operation class to copy jni function table at safepoint.
 102 // More than one java threads or jvmti agents may be reading/
 103 // modifying jni function tables. To reduce the risk of bad
 104 // interaction b/w these threads it is copied at safepoint.
 105 class VM_JNIFunctionTableCopier : public VM_Operation {
 106  private:
 107   const struct JNINativeInterface_ *_function_table;
 108  public:
 109   VM_JNIFunctionTableCopier(const struct JNINativeInterface_ *func_tbl) {
 110     _function_table = func_tbl;
 111   };
 112 
 113   VMOp_Type type() const { return VMOp_JNIFunctionTableCopier; }
 114   void doit() {
 115     copy_jni_function_table(_function_table);
 116   };
 117 };
 118 
 119 //
 120 // Do not change the "prefix" marker below, everything above it is copied
 121 // unchanged into the filled stub, everything below is controlled by the
 122 // stub filler (only method bodies are carried forward, and then only for
 123 // functionality still in the spec).
 124 //
 125 // end file prefix
 126 
 127   //
 128   // Memory Management functions
 129   //
 130 
 131 // mem_ptr - pre-checked for NULL
 132 jvmtiError
 133 JvmtiEnv::Allocate(jlong size, unsigned char** mem_ptr) {
 134   return allocate(size, mem_ptr);
 135 } /* end Allocate */
 136 
 137 
 138 // mem - NULL is a valid value, must be checked
 139 jvmtiError
 140 JvmtiEnv::Deallocate(unsigned char* mem) {
 141   return deallocate(mem);
 142 } /* end Deallocate */
 143 
 144 // Threads_lock NOT held
 145 // data - NULL is a valid value, must be checked
 146 jvmtiError
 147 JvmtiEnv::SetThreadLocalStorage(jthread thread, const void* data) {
 148   jvmtiError err = JVMTI_ERROR_NONE;
 149   JavaThread* java_thread = NULL;
 150   JvmtiThreadState* state = NULL;
 151   JvmtiVTMTDisabler vtmt_disabler;
 152   oop thread_obj = NULL;
 153   JavaThread* current = JavaThread::current();
 154 
 155   if (thread == NULL) {
 156     java_thread = current;
 157     state = java_thread->jvmti_thread_state();
 158   } else {
 159     ThreadsListHandle tlh;
 160     err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
 161     if (err != JVMTI_ERROR_NONE) {
 162       return err;
 163     }
 164     state = java_lang_Thread::jvmti_thread_state(thread_obj);
 165   }
 166   if (state == NULL) {
 167     if (data == NULL) {
 168       // leaving state unset same as data set to NULL
 169       return JVMTI_ERROR_NONE;
 170     }
 171     // otherwise, create the state
 172     HandleMark hm(current);
 173     Handle thread_handle(current, thread_obj);
 174     state = JvmtiThreadState::state_for(java_thread, thread_handle);
 175     if (state == NULL) {
 176       return JVMTI_ERROR_THREAD_NOT_ALIVE;
 177     }
 178   }
 179   state->env_thread_state(this)->set_agent_thread_local_storage_data((void*)data);
 180   return JVMTI_ERROR_NONE;
 181 } /* end SetThreadLocalStorage */
 182 
 183 
 184 // data_ptr - pre-checked for NULL
 185 jvmtiError
 186 JvmtiEnv::GetThreadLocalStorage(jthread thread, void** data_ptr) {
 187   JavaThread* current_thread = JavaThread::current();
 188   if (thread == NULL) {
 189     JvmtiThreadState* state = current_thread->jvmti_thread_state();
 190     *data_ptr = (state == NULL) ? NULL :
 191       state->env_thread_state(this)->get_agent_thread_local_storage_data();
 192   } else {
 193     // jvmti_GetThreadLocalStorage is "in native" and doesn't transition
 194     // the thread to _thread_in_vm. However, when the TLS for a thread
 195     // other than the current thread is required we need to transition
 196     // from native so as to resolve the jthread.
 197 
 198     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, current_thread));
 199     ThreadInVMfromNative __tiv(current_thread);
 200     VM_ENTRY_BASE(jvmtiError, JvmtiEnv::GetThreadLocalStorage , current_thread)
 201     debug_only(VMNativeEntryWrapper __vew;)
 202 
 203     JavaThread* java_thread = NULL;
 204     oop thread_obj = NULL;
 205     JvmtiVTMTDisabler vtmt_disabler;
 206     ThreadsListHandle tlh(current_thread);
 207 
 208     jvmtiError err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
 209     if (err != JVMTI_ERROR_NONE) {
 210       return err;
 211     }
 212 
 213     HandleMark hm(current_thread);
 214     Handle thread_handle(current_thread, thread_obj);
 215     JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread, thread_handle);
 216     *data_ptr = (state == NULL) ? NULL :
 217       state->env_thread_state(this)->get_agent_thread_local_storage_data();
 218   }
 219   return JVMTI_ERROR_NONE;
 220 } /* end GetThreadLocalStorage */
 221 
 222   //
 223   // Module functions
 224   //
 225 
 226 // module_count_ptr - pre-checked for NULL
 227 // modules_ptr - pre-checked for NULL
 228 jvmtiError
 229 JvmtiEnv::GetAllModules(jint* module_count_ptr, jobject** modules_ptr) {
 230     JvmtiModuleClosure jmc;
 231 
 232     return jmc.get_all_modules(this, module_count_ptr, modules_ptr);
 233 } /* end GetAllModules */
 234 
 235 
 236 // class_loader - NULL is a valid value, must be pre-checked
 237 // package_name - pre-checked for NULL
 238 // module_ptr - pre-checked for NULL
 239 jvmtiError
 240 JvmtiEnv::GetNamedModule(jobject class_loader, const char* package_name, jobject* module_ptr) {
 241   JavaThread* THREAD = JavaThread::current(); // For exception macros.
 242   ResourceMark rm(THREAD);
 243 
 244   Handle h_loader (THREAD, JNIHandles::resolve(class_loader));
 245   // Check that loader is a subclass of java.lang.ClassLoader.
 246   if (h_loader.not_null() && !java_lang_ClassLoader::is_subclass(h_loader->klass())) {
 247     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 248   }
 249   oop module = Modules::get_named_module(h_loader, package_name);
 250   *module_ptr = module != NULL ? JNIHandles::make_local(THREAD, module) : NULL;
 251   return JVMTI_ERROR_NONE;
 252 } /* end GetNamedModule */
 253 
 254 
 255 // module - pre-checked for NULL
 256 // to_module - pre-checked for NULL
 257 jvmtiError
 258 JvmtiEnv::AddModuleReads(jobject module, jobject to_module) {
 259   JavaThread* THREAD = JavaThread::current(); // For exception macros.
 260 
 261   // check module
 262   Handle h_module(THREAD, JNIHandles::resolve(module));
 263   if (!java_lang_Module::is_instance(h_module())) {
 264     return JVMTI_ERROR_INVALID_MODULE;
 265   }
 266   // check to_module
 267   Handle h_to_module(THREAD, JNIHandles::resolve(to_module));
 268   if (!java_lang_Module::is_instance(h_to_module())) {
 269     return JVMTI_ERROR_INVALID_MODULE;
 270   }
 271   return JvmtiExport::add_module_reads(h_module, h_to_module, THREAD);
 272 } /* end AddModuleReads */
 273 
 274 
 275 // module - pre-checked for NULL
 276 // pkg_name - pre-checked for NULL
 277 // to_module - pre-checked for NULL
 278 jvmtiError
 279 JvmtiEnv::AddModuleExports(jobject module, const char* pkg_name, jobject to_module) {
 280   JavaThread* THREAD = JavaThread::current(); // For exception macros.
 281   Handle h_pkg = java_lang_String::create_from_str(pkg_name, THREAD);
 282 
 283   // check module
 284   Handle h_module(THREAD, JNIHandles::resolve(module));
 285   if (!java_lang_Module::is_instance(h_module())) {
 286     return JVMTI_ERROR_INVALID_MODULE;
 287   }
 288   // check to_module
 289   Handle h_to_module(THREAD, JNIHandles::resolve(to_module));
 290   if (!java_lang_Module::is_instance(h_to_module())) {
 291     return JVMTI_ERROR_INVALID_MODULE;
 292   }
 293   return JvmtiExport::add_module_exports(h_module, h_pkg, h_to_module, THREAD);
 294 } /* end AddModuleExports */
 295 
 296 
 297 // module - pre-checked for NULL
 298 // pkg_name - pre-checked for NULL
 299 // to_module - pre-checked for NULL
 300 jvmtiError
 301 JvmtiEnv::AddModuleOpens(jobject module, const char* pkg_name, jobject to_module) {
 302   JavaThread* THREAD = JavaThread::current(); // For exception macros.
 303   Handle h_pkg = java_lang_String::create_from_str(pkg_name, THREAD);
 304 
 305   // check module
 306   Handle h_module(THREAD, JNIHandles::resolve(module));
 307   if (!java_lang_Module::is_instance(h_module())) {
 308     return JVMTI_ERROR_INVALID_MODULE;
 309   }
 310   // check to_module
 311   Handle h_to_module(THREAD, JNIHandles::resolve(to_module));
 312   if (!java_lang_Module::is_instance(h_to_module())) {
 313     return JVMTI_ERROR_INVALID_MODULE;
 314   }
 315   return JvmtiExport::add_module_opens(h_module, h_pkg, h_to_module, THREAD);
 316 } /* end AddModuleOpens */
 317 
 318 
 319 // module - pre-checked for NULL
 320 // service - pre-checked for NULL
 321 jvmtiError
 322 JvmtiEnv::AddModuleUses(jobject module, jclass service) {
 323   JavaThread* THREAD = JavaThread::current(); // For exception macros.
 324 
 325   // check module
 326   Handle h_module(THREAD, JNIHandles::resolve(module));
 327   if (!java_lang_Module::is_instance(h_module())) {
 328     return JVMTI_ERROR_INVALID_MODULE;
 329   }
 330   // check service
 331   Handle h_service(THREAD, JNIHandles::resolve_external_guard(service));
 332   if (!java_lang_Class::is_instance(h_service()) ||
 333       java_lang_Class::is_primitive(h_service())) {
 334     return JVMTI_ERROR_INVALID_CLASS;
 335   }
 336   return JvmtiExport::add_module_uses(h_module, h_service, THREAD);
 337 } /* end AddModuleUses */
 338 
 339 
 340 // module - pre-checked for NULL
 341 // service - pre-checked for NULL
 342 // impl_class - pre-checked for NULL
 343 jvmtiError
 344 JvmtiEnv::AddModuleProvides(jobject module, jclass service, jclass impl_class) {
 345   JavaThread* THREAD = JavaThread::current(); // For exception macros.
 346 
 347   // check module
 348   Handle h_module(THREAD, JNIHandles::resolve(module));
 349   if (!java_lang_Module::is_instance(h_module())) {
 350     return JVMTI_ERROR_INVALID_MODULE;
 351   }
 352   // check service
 353   Handle h_service(THREAD, JNIHandles::resolve_external_guard(service));
 354   if (!java_lang_Class::is_instance(h_service()) ||
 355       java_lang_Class::is_primitive(h_service())) {
 356     return JVMTI_ERROR_INVALID_CLASS;
 357   }
 358   // check impl_class
 359   Handle h_impl_class(THREAD, JNIHandles::resolve_external_guard(impl_class));
 360   if (!java_lang_Class::is_instance(h_impl_class()) ||
 361       java_lang_Class::is_primitive(h_impl_class())) {
 362     return JVMTI_ERROR_INVALID_CLASS;
 363   }
 364   return JvmtiExport::add_module_provides(h_module, h_service, h_impl_class, THREAD);
 365 } /* end AddModuleProvides */
 366 
 367 // module - pre-checked for NULL
 368 // is_modifiable_class_ptr - pre-checked for NULL
 369 jvmtiError
 370 JvmtiEnv::IsModifiableModule(jobject module, jboolean* is_modifiable_module_ptr) {
 371   JavaThread* current = JavaThread::current();
 372 
 373   // check module
 374   Handle h_module(current, JNIHandles::resolve(module));
 375   if (!java_lang_Module::is_instance(h_module())) {
 376     return JVMTI_ERROR_INVALID_MODULE;
 377   }
 378 
 379   *is_modifiable_module_ptr = JNI_TRUE;
 380   return JVMTI_ERROR_NONE;
 381 } /* end IsModifiableModule */
 382 
 383 
 384   //
 385   // Class functions
 386   //
 387 
 388 // class_count_ptr - pre-checked for NULL
 389 // classes_ptr - pre-checked for NULL
 390 jvmtiError
 391 JvmtiEnv::GetLoadedClasses(jint* class_count_ptr, jclass** classes_ptr) {
 392   return JvmtiGetLoadedClasses::getLoadedClasses(this, class_count_ptr, classes_ptr);
 393 } /* end GetLoadedClasses */
 394 
 395 
 396 // initiating_loader - NULL is a valid value, must be checked
 397 // class_count_ptr - pre-checked for NULL
 398 // classes_ptr - pre-checked for NULL
 399 jvmtiError
 400 JvmtiEnv::GetClassLoaderClasses(jobject initiating_loader, jint* class_count_ptr, jclass** classes_ptr) {
 401   return JvmtiGetLoadedClasses::getClassLoaderClasses(this, initiating_loader,
 402                                                   class_count_ptr, classes_ptr);
 403 } /* end GetClassLoaderClasses */
 404 
 405 // k_mirror - may be primitive, this must be checked
 406 // is_modifiable_class_ptr - pre-checked for NULL
 407 jvmtiError
 408 JvmtiEnv::IsModifiableClass(oop k_mirror, jboolean* is_modifiable_class_ptr) {
 409   *is_modifiable_class_ptr = VM_RedefineClasses::is_modifiable_class(k_mirror)?
 410                                                        JNI_TRUE : JNI_FALSE;
 411   return JVMTI_ERROR_NONE;
 412 } /* end IsModifiableClass */
 413 
 414 // class_count - pre-checked to be greater than or equal to 0
 415 // classes - pre-checked for NULL
 416 jvmtiError
 417 JvmtiEnv::RetransformClasses(jint class_count, const jclass* classes) {
 418 //TODO: add locking
 419 
 420   int index;
 421   JavaThread* current_thread = JavaThread::current();
 422   ResourceMark rm(current_thread);
 423 
 424   jvmtiClassDefinition* class_definitions =
 425                             NEW_RESOURCE_ARRAY(jvmtiClassDefinition, class_count);
 426   NULL_CHECK(class_definitions, JVMTI_ERROR_OUT_OF_MEMORY);
 427 
 428   for (index = 0; index < class_count; index++) {
 429     HandleMark hm(current_thread);
 430 
 431     jclass jcls = classes[index];
 432     oop k_mirror = JNIHandles::resolve_external_guard(jcls);
 433     if (k_mirror == NULL) {
 434       return JVMTI_ERROR_INVALID_CLASS;
 435     }
 436     if (!k_mirror->is_a(vmClasses::Class_klass())) {
 437       return JVMTI_ERROR_INVALID_CLASS;
 438     }
 439 
 440     if (!VM_RedefineClasses::is_modifiable_class(k_mirror)) {
 441       return JVMTI_ERROR_UNMODIFIABLE_CLASS;
 442     }
 443 
 444     Klass* klass = java_lang_Class::as_Klass(k_mirror);
 445 
 446     jint status = klass->jvmti_class_status();
 447     if (status & (JVMTI_CLASS_STATUS_ERROR)) {
 448       return JVMTI_ERROR_INVALID_CLASS;
 449     }
 450 
 451     InstanceKlass* ik = InstanceKlass::cast(klass);
 452     if (ik->get_cached_class_file_bytes() == NULL) {
 453       // Not cached, we need to reconstitute the class file from the
 454       // VM representation. We don't attach the reconstituted class
 455       // bytes to the InstanceKlass here because they have not been
 456       // validated and we're not at a safepoint.
 457       JvmtiClassFileReconstituter reconstituter(ik);
 458       if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
 459         return reconstituter.get_error();
 460       }
 461 
 462       class_definitions[index].class_byte_count = (jint)reconstituter.class_file_size();
 463       class_definitions[index].class_bytes      = (unsigned char*)
 464                                                        reconstituter.class_file_bytes();
 465     } else {
 466       // it is cached, get it from the cache
 467       class_definitions[index].class_byte_count = ik->get_cached_class_file_len();
 468       class_definitions[index].class_bytes      = ik->get_cached_class_file_bytes();
 469     }
 470     class_definitions[index].klass              = jcls;
 471   }
 472   EventRetransformClasses event;
 473   VM_RedefineClasses op(class_count, class_definitions, jvmti_class_load_kind_retransform);
 474   VMThread::execute(&op);
 475   jvmtiError error = op.check_error();
 476   if (error == JVMTI_ERROR_NONE) {
 477     event.set_classCount(class_count);
 478     event.set_redefinitionId(op.id());
 479     event.commit();
 480   }
 481   return error;
 482 } /* end RetransformClasses */
 483 
 484 
 485 // class_count - pre-checked to be greater than or equal to 0
 486 // class_definitions - pre-checked for NULL
 487 jvmtiError
 488 JvmtiEnv::RedefineClasses(jint class_count, const jvmtiClassDefinition* class_definitions) {
 489 //TODO: add locking
 490   EventRedefineClasses event;
 491   VM_RedefineClasses op(class_count, class_definitions, jvmti_class_load_kind_redefine);
 492   VMThread::execute(&op);
 493   jvmtiError error = op.check_error();
 494   if (error == JVMTI_ERROR_NONE) {
 495     event.set_classCount(class_count);
 496     event.set_redefinitionId(op.id());
 497     event.commit();
 498   }
 499   return error;
 500 } /* end RedefineClasses */
 501 
 502 
 503   //
 504   // Object functions
 505   //
 506 
 507 // size_ptr - pre-checked for NULL
 508 jvmtiError
 509 JvmtiEnv::GetObjectSize(jobject object, jlong* size_ptr) {
 510   oop mirror = JNIHandles::resolve_external_guard(object);
 511   NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
 512   *size_ptr = (jlong)mirror->size() * wordSize;
 513   return JVMTI_ERROR_NONE;
 514 } /* end GetObjectSize */
 515 
 516   //
 517   // Method functions
 518   //
 519 
 520 // prefix - NULL is a valid value, must be checked
 521 jvmtiError
 522 JvmtiEnv::SetNativeMethodPrefix(const char* prefix) {
 523   return prefix == NULL?
 524               SetNativeMethodPrefixes(0, NULL) :
 525               SetNativeMethodPrefixes(1, (char**)&prefix);
 526 } /* end SetNativeMethodPrefix */
 527 
 528 
 529 // prefix_count - pre-checked to be greater than or equal to 0
 530 // prefixes - pre-checked for NULL
 531 jvmtiError
 532 JvmtiEnv::SetNativeMethodPrefixes(jint prefix_count, char** prefixes) {
 533   // Have to grab JVMTI thread state lock to be sure that some thread
 534   // isn't accessing the prefixes at the same time we are setting them.
 535   // No locks during VM bring-up.
 536   if (Threads::number_of_threads() == 0) {
 537     return set_native_method_prefixes(prefix_count, prefixes);
 538   } else {
 539     MutexLocker mu(JvmtiThreadState_lock);
 540     return set_native_method_prefixes(prefix_count, prefixes);
 541   }
 542 } /* end SetNativeMethodPrefixes */
 543 
 544   //
 545   // Event Management functions
 546   //
 547 
 548 // callbacks - NULL is a valid value, must be checked
 549 // size_of_callbacks - pre-checked to be greater than or equal to 0
 550 jvmtiError
 551 JvmtiEnv::SetEventCallbacks(const jvmtiEventCallbacks* callbacks, jint size_of_callbacks) {
 552   JvmtiEventController::set_event_callbacks(this, callbacks, size_of_callbacks);
 553   return JVMTI_ERROR_NONE;
 554 } /* end SetEventCallbacks */
 555 
 556 
 557 // event_thread - NULL is a valid value, must be checked
 558 jvmtiError
 559 JvmtiEnv::SetEventNotificationMode(jvmtiEventMode mode, jvmtiEvent event_type, jthread event_thread,   ...) {
 560   bool enabled = (mode == JVMTI_ENABLE);
 561 
 562   // event_type must be valid
 563   if (!JvmtiEventController::is_valid_event_type(event_type)) {
 564     return JVMTI_ERROR_INVALID_EVENT_TYPE;
 565   }
 566 
 567   // assure that needed capabilities are present
 568   if (enabled && !JvmtiUtil::has_event_capability(event_type, get_capabilities())) {
 569     return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
 570   }
 571 
 572   if (event_type == JVMTI_EVENT_CLASS_FILE_LOAD_HOOK && enabled) {
 573     record_class_file_load_hook_enabled();
 574   }
 575 
 576   if (event_thread == NULL) {
 577     // Can be called at Agent_OnLoad() time with event_thread == NULL
 578     // when Thread::current() does not work yet so we cannot create a
 579     // ThreadsListHandle that is common to both thread-specific and
 580     // global code paths.
 581 
 582     JvmtiEventController::set_user_enabled(this, (JavaThread*) NULL, (oop) NULL, event_type, enabled);
 583   } else {
 584     // We have a specified event_thread.
 585     JavaThread* java_thread = NULL;
 586     oop thread_obj = NULL;
 587     JvmtiVTMTDisabler vtmt_disabler;
 588     ThreadsListHandle tlh;
 589 
 590     jvmtiError err = get_threadOop_and_JavaThread(tlh.list(), event_thread, &java_thread, &thread_obj);
 591     if (err != JVMTI_ERROR_NONE) {
 592       return err;
 593     }
 594 
 595     // global events cannot be controlled at thread level.
 596     if (JvmtiEventController::is_global_event(event_type)) {
 597       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 598     }
 599 
 600     JvmtiEventController::set_user_enabled(this, java_thread, thread_obj, event_type, enabled);
 601   }
 602 
 603   return JVMTI_ERROR_NONE;
 604 } /* end SetEventNotificationMode */
 605 
 606   //
 607   // Capability functions
 608   //
 609 
 610 // capabilities_ptr - pre-checked for NULL
 611 jvmtiError
 612 JvmtiEnv::GetPotentialCapabilities(jvmtiCapabilities* capabilities_ptr) {
 613   JvmtiManageCapabilities::get_potential_capabilities(get_capabilities(),
 614                                                       get_prohibited_capabilities(),
 615                                                       capabilities_ptr);
 616   return JVMTI_ERROR_NONE;
 617 } /* end GetPotentialCapabilities */
 618 
 619 
 620 // capabilities_ptr - pre-checked for NULL
 621 jvmtiError
 622 JvmtiEnv::AddCapabilities(const jvmtiCapabilities* capabilities_ptr) {
 623   return JvmtiManageCapabilities::add_capabilities(get_capabilities(),
 624                                                    get_prohibited_capabilities(),
 625                                                    capabilities_ptr,
 626                                                    get_capabilities());
 627 } /* end AddCapabilities */
 628 
 629 
 630 // capabilities_ptr - pre-checked for NULL
 631 jvmtiError
 632 JvmtiEnv::RelinquishCapabilities(const jvmtiCapabilities* capabilities_ptr) {
 633   JvmtiManageCapabilities::relinquish_capabilities(get_capabilities(), capabilities_ptr, get_capabilities());
 634   return JVMTI_ERROR_NONE;
 635 } /* end RelinquishCapabilities */
 636 
 637 
 638 // capabilities_ptr - pre-checked for NULL
 639 jvmtiError
 640 JvmtiEnv::GetCapabilities(jvmtiCapabilities* capabilities_ptr) {
 641   JvmtiManageCapabilities::copy_capabilities(get_capabilities(), capabilities_ptr);
 642   return JVMTI_ERROR_NONE;
 643 } /* end GetCapabilities */
 644 
 645   //
 646   // Class Loader Search functions
 647   //
 648 
 649 // segment - pre-checked for NULL
 650 jvmtiError
 651 JvmtiEnv::AddToBootstrapClassLoaderSearch(const char* segment) {
 652   jvmtiPhase phase = get_phase();
 653   if (phase == JVMTI_PHASE_ONLOAD) {
 654     Arguments::append_sysclasspath(segment);
 655     return JVMTI_ERROR_NONE;
 656   } else if (use_version_1_0_semantics()) {
 657     // This JvmtiEnv requested version 1.0 semantics and this function
 658     // is only allowed in the ONLOAD phase in version 1.0 so we need to
 659     // return an error here.
 660     return JVMTI_ERROR_WRONG_PHASE;
 661   } else if (phase == JVMTI_PHASE_LIVE) {
 662     // The phase is checked by the wrapper that called this function,
 663     // but this thread could be racing with the thread that is
 664     // terminating the VM so we check one more time.
 665 
 666     // create the zip entry
 667     ClassPathZipEntry* zip_entry = ClassLoader::create_class_path_zip_entry(segment, true);
 668     if (zip_entry == NULL) {
 669       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 670     }
 671 
 672     // add the jar file to the bootclasspath
 673     log_info(class, load)("opened: %s", zip_entry->name());
 674 #if INCLUDE_CDS
 675     ClassLoaderExt::append_boot_classpath(zip_entry);
 676 #else
 677     ClassLoader::add_to_boot_append_entries(zip_entry);
 678 #endif
 679     return JVMTI_ERROR_NONE;
 680   } else {
 681     return JVMTI_ERROR_WRONG_PHASE;
 682   }
 683 
 684 } /* end AddToBootstrapClassLoaderSearch */
 685 
 686 
 687 // segment - pre-checked for NULL
 688 jvmtiError
 689 JvmtiEnv::AddToSystemClassLoaderSearch(const char* segment) {
 690   jvmtiPhase phase = get_phase();
 691 
 692   if (phase == JVMTI_PHASE_ONLOAD) {
 693     for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
 694       if (strcmp("java.class.path", p->key()) == 0) {
 695         p->append_value(segment);
 696         break;
 697       }
 698     }
 699     return JVMTI_ERROR_NONE;
 700   } else if (phase == JVMTI_PHASE_LIVE) {
 701     // The phase is checked by the wrapper that called this function,
 702     // but this thread could be racing with the thread that is
 703     // terminating the VM so we check one more time.
 704     JavaThread* THREAD = JavaThread::current(); // For exception macros.
 705     HandleMark hm(THREAD);
 706 
 707     // create the zip entry (which will open the zip file and hence
 708     // check that the segment is indeed a zip file).
 709     ClassPathZipEntry* zip_entry = ClassLoader::create_class_path_zip_entry(segment, false);
 710     if (zip_entry == NULL) {
 711       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 712     }
 713     delete zip_entry;   // no longer needed
 714 
 715     // lock the loader
 716     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 717     ObjectLocker ol(loader, THREAD);
 718 
 719     // need the path as java.lang.String
 720     Handle path = java_lang_String::create_from_platform_dependent_str(segment, THREAD);
 721     if (HAS_PENDING_EXCEPTION) {
 722       CLEAR_PENDING_EXCEPTION;
 723       return JVMTI_ERROR_INTERNAL;
 724     }
 725 
 726     // Invoke the appendToClassPathForInstrumentation method - if the method
 727     // is not found it means the loader doesn't support adding to the class path
 728     // in the live phase.
 729     {
 730       JavaValue res(T_VOID);
 731       JavaCalls::call_special(&res,
 732                               loader,
 733                               loader->klass(),
 734                               vmSymbols::appendToClassPathForInstrumentation_name(),
 735                               vmSymbols::appendToClassPathForInstrumentation_signature(),
 736                               path,
 737                               THREAD);
 738       if (HAS_PENDING_EXCEPTION) {
 739         Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
 740         CLEAR_PENDING_EXCEPTION;
 741 
 742         if (ex_name == vmSymbols::java_lang_NoSuchMethodError()) {
 743           return JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED;
 744         } else {
 745           return JVMTI_ERROR_INTERNAL;
 746         }
 747       }
 748     }
 749 
 750     return JVMTI_ERROR_NONE;
 751   } else {
 752     return JVMTI_ERROR_WRONG_PHASE;
 753   }
 754 } /* end AddToSystemClassLoaderSearch */
 755 
 756   //
 757   // General functions
 758   //
 759 
 760 // phase_ptr - pre-checked for NULL
 761 jvmtiError
 762 JvmtiEnv::GetPhase(jvmtiPhase* phase_ptr) {
 763   *phase_ptr = phase();
 764   return JVMTI_ERROR_NONE;
 765 } /* end GetPhase */
 766 
 767 
 768 jvmtiError
 769 JvmtiEnv::DisposeEnvironment() {
 770   dispose();
 771   return JVMTI_ERROR_NONE;
 772 } /* end DisposeEnvironment */
 773 
 774 
 775 // data - NULL is a valid value, must be checked
 776 jvmtiError
 777 JvmtiEnv::SetEnvironmentLocalStorage(const void* data) {
 778   set_env_local_storage(data);
 779   return JVMTI_ERROR_NONE;
 780 } /* end SetEnvironmentLocalStorage */
 781 
 782 
 783 // data_ptr - pre-checked for NULL
 784 jvmtiError
 785 JvmtiEnv::GetEnvironmentLocalStorage(void** data_ptr) {
 786   *data_ptr = (void*)get_env_local_storage();
 787   return JVMTI_ERROR_NONE;
 788 } /* end GetEnvironmentLocalStorage */
 789 
 790 // version_ptr - pre-checked for NULL
 791 jvmtiError
 792 JvmtiEnv::GetVersionNumber(jint* version_ptr) {
 793   *version_ptr = JVMTI_VERSION;
 794   return JVMTI_ERROR_NONE;
 795 } /* end GetVersionNumber */
 796 
 797 
 798 // name_ptr - pre-checked for NULL
 799 jvmtiError
 800 JvmtiEnv::GetErrorName(jvmtiError error, char** name_ptr) {
 801   if (error < JVMTI_ERROR_NONE || error > JVMTI_ERROR_MAX) {
 802     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 803   }
 804   const char *name = JvmtiUtil::error_name(error);
 805   if (name == NULL) {
 806     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 807   }
 808   size_t len = strlen(name) + 1;
 809   jvmtiError err = allocate(len, (unsigned char**)name_ptr);
 810   if (err == JVMTI_ERROR_NONE) {
 811     memcpy(*name_ptr, name, len);
 812   }
 813   return err;
 814 } /* end GetErrorName */
 815 
 816 
 817 jvmtiError
 818 JvmtiEnv::SetVerboseFlag(jvmtiVerboseFlag flag, jboolean value) {
 819   LogLevelType level = value == 0 ? LogLevel::Off : LogLevel::Info;
 820   switch (flag) {
 821   case JVMTI_VERBOSE_OTHER:
 822     // ignore
 823     break;
 824   case JVMTI_VERBOSE_CLASS:
 825     LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, unload));
 826     LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, load));
 827     break;
 828   case JVMTI_VERBOSE_GC:
 829     LogConfiguration::configure_stdout(level, true, LOG_TAGS(gc));
 830     break;
 831   case JVMTI_VERBOSE_JNI:
 832     level = value == 0 ? LogLevel::Off : LogLevel::Debug;
 833     LogConfiguration::configure_stdout(level, true, LOG_TAGS(jni, resolve));
 834     break;
 835   default:
 836     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 837   };
 838   return JVMTI_ERROR_NONE;
 839 } /* end SetVerboseFlag */
 840 
 841 
 842 // format_ptr - pre-checked for NULL
 843 jvmtiError
 844 JvmtiEnv::GetJLocationFormat(jvmtiJlocationFormat* format_ptr) {
 845   *format_ptr = JVMTI_JLOCATION_JVMBCI;
 846   return JVMTI_ERROR_NONE;
 847 } /* end GetJLocationFormat */
 848 
 849   //
 850   // Thread functions
 851   //
 852 
 853 // thread_state_ptr - pre-checked for NULL
 854 jvmtiError
 855 JvmtiEnv::GetThreadState(jthread thread, jint* thread_state_ptr) {
 856   JavaThread* current_thread = JavaThread::current();
 857   JavaThread* java_thread = NULL;
 858   oop thread_oop = NULL;
 859   JvmtiVTMTDisabler vtmt_disabler;
 860   ThreadsListHandle tlh(current_thread);
 861 
 862   if (thread == NULL) {
 863     java_thread = current_thread;
 864     thread_oop = get_vthread_or_thread_oop(java_thread);
 865 
 866     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::Thread_klass())) {
 867       return JVMTI_ERROR_INVALID_THREAD;
 868     }
 869   } else {
 870     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
 871     if (err != JVMTI_ERROR_NONE) {
 872       // We got an error code so we don't have a JavaThread *, but
 873       // only return an error from here if we didn't get a valid
 874       // thread_oop.
 875       // In a vthread case the cv_external_thread_to_JavaThread is expected to correctly set
 876       // the thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
 877       if (thread_oop == NULL) {
 878         return err;
 879       }
 880       // We have a valid thread_oop so we can return some thread state.
 881     }
 882   }
 883 
 884   // Support for virtual thread
 885   if (java_lang_VirtualThread::is_instance(thread_oop)) {
 886     *thread_state_ptr = JvmtiEnvBase::get_vthread_state(thread_oop);
 887   } else {
 888     *thread_state_ptr = JvmtiEnvBase::get_thread_state(thread_oop, java_thread);
 889   }
 890   // java_thread can be suspended only if its virtual or carrier thread object is suspended.
 891   assert(java_thread == NULL || !java_thread->is_suspended() ||
 892          (*thread_state_ptr | JVMTI_THREAD_STATE_SUSPENDED) != 0, "sanity check");
 893   return JVMTI_ERROR_NONE;
 894 } /* end GetThreadState */
 895 
 896 
 897 // thread_ptr - pre-checked for NULL
 898 jvmtiError
 899 JvmtiEnv::GetCurrentThread(jthread* thread_ptr) {
 900   JavaThread* cur_thread = JavaThread::current();
 901   oop thread_oop = get_vthread_or_thread_oop(cur_thread);
 902 
 903   *thread_ptr = (jthread)JNIHandles::make_local(cur_thread, thread_oop);
 904   return JVMTI_ERROR_NONE;
 905 } /* end GetCurrentThread */
 906 
 907 
 908 // threads_count_ptr - pre-checked for NULL
 909 // threads_ptr - pre-checked for NULL
 910 jvmtiError
 911 JvmtiEnv::GetAllThreads(jint* threads_count_ptr, jthread** threads_ptr) {
 912   int nthreads        = 0;
 913   Handle *thread_objs = NULL;
 914   Thread* current_thread = Thread::current();
 915   ResourceMark rm(current_thread);
 916   HandleMark hm(current_thread);
 917 
 918   // enumerate threads (including agent threads)
 919   ThreadsListEnumerator tle(current_thread, true);
 920   nthreads = tle.num_threads();
 921   *threads_count_ptr = nthreads;
 922 
 923   if (nthreads == 0) {
 924     *threads_ptr = NULL;
 925     return JVMTI_ERROR_NONE;
 926   }
 927 
 928   thread_objs = NEW_RESOURCE_ARRAY(Handle, nthreads);
 929   NULL_CHECK(thread_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 930 
 931   for (int i = 0; i < nthreads; i++) {
 932     thread_objs[i] = Handle(tle.get_threadObj(i));
 933   }
 934 
 935   jthread *jthreads  = new_jthreadArray(nthreads, thread_objs);
 936   NULL_CHECK(jthreads, JVMTI_ERROR_OUT_OF_MEMORY);
 937 
 938   *threads_ptr = jthreads;
 939   return JVMTI_ERROR_NONE;
 940 } /* end GetAllThreads */
 941 
 942 
 943 jvmtiError
 944 JvmtiEnv::SuspendThread(jthread thread) {
 945   JavaThread* java_thread = NULL;
 946   oop thread_oop = NULL;
 947   JvmtiVTMTDisabler vtmt_disabler;
 948   ThreadsListHandle tlh;
 949 
 950   jvmtiError err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
 951   if (err != JVMTI_ERROR_NONE) {
 952     return err;
 953   }
 954   if (java_thread != NULL && java_thread == JavaThread::current()) {
 955     // current thread will be suspended in the ~JvmtiVTMTDisabler
 956     vtmt_disabler.set_self_suspend();
 957   }
 958   err = suspend_thread(thread_oop,
 959                        java_thread,
 960                        true,  // single suspend
 961                        NULL); // no need for extra safepoint
 962   return err;
 963 } /* end SuspendThread */
 964 
 965 
 966 // request_count - pre-checked to be greater than or equal to 0
 967 // request_list - pre-checked for NULL
 968 // results - pre-checked for NULL
 969 jvmtiError
 970 JvmtiEnv::SuspendThreadList(jint request_count, const jthread* request_list, jvmtiError* results) {
 971   oop thread_oop = NULL;
 972   JavaThread *java_thread = NULL;
 973   JavaThread* current = JavaThread::current();
 974 
 975   JvmtiVTMTDisabler vtmt_disabler;
 976   ThreadsListHandle tlh(current);
 977 
 978   for (int i = 0; i < request_count; i++) {
 979     jthread thread = request_list[i];
 980     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
 981     if (err != JVMTI_ERROR_NONE) {
 982       if (thread_oop == NULL || err != JVMTI_ERROR_INVALID_THREAD) {
 983         results[i] = err;
 984         continue;
 985       }
 986     }
 987     if (java_thread == current) {
 988       // current thread will be suspended in the ~JvmtiVTMTDisabler
 989       vtmt_disabler.set_self_suspend();
 990     }
 991     results[i] = suspend_thread(thread_oop,
 992                                 java_thread,
 993                                 true, // single suspend
 994                                 NULL);
 995   }
 996   // per-thread suspend results returned via results parameter
 997   return JVMTI_ERROR_NONE;
 998 } /* end SuspendThreadList */
 999 
1000 
1001 jvmtiError
1002 JvmtiEnv::SuspendAllVirtualThreads(jint except_count, const jthread* except_list) {
1003   jvmtiError err = JvmtiEnvBase::check_thread_list(except_count, except_list);
1004   if (err != JVMTI_ERROR_NONE) {
1005     return err;
1006   }
1007   if (!JvmtiExport::can_support_virtual_threads()) {
1008     return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
1009   }
1010   ResourceMark rm;
1011   JvmtiVTMTDisabler vtmt_disabler;
1012   GrowableArray<jthread>* elist = new GrowableArray<jthread>(except_count);
1013 
1014   // Collect threads from except_list which resumed status must be restored.
1015   for (int idx = 0; idx < except_count; idx++) {
1016     jthread thread = except_list[idx];
1017     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1018     if (!JvmtiVTSuspender::is_vthread_suspended(thread_oop)) {
1019         // is resumed, so its resumed status must be restored
1020         elist->append(except_list[idx]);
1021     }
1022   }
1023 
1024   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *java_thread = jtiwh.next(); ) {
1025     oop vt_oop = java_thread->mounted_vthread();
1026     if (!java_thread->is_exiting() &&
1027         !java_thread->is_jvmti_agent_thread() &&
1028         !java_thread->is_hidden_from_external_view() &&
1029         vt_oop != NULL &&
1030         java_lang_VirtualThread::is_instance(vt_oop) &&
1031         JvmtiEnvBase::is_vthread_alive(vt_oop) &&
1032         !JvmtiVTSuspender::is_vthread_suspended(vt_oop) &&
1033         !is_in_thread_list(except_count, except_list, vt_oop)
1034     ) {
1035       suspend_thread(vt_oop,
1036                      java_thread,
1037                      false, // suspend all
1038                      NULL);
1039     }
1040   }
1041   JvmtiVTSuspender::register_all_vthreads_suspend();
1042 
1043   // Restore resumed state for threads from except list that were resumed before.
1044   for (int idx = 0; idx < elist->length(); idx++) {
1045     jthread thread = elist->at(idx);
1046     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1047     if (JvmtiVTSuspender::is_vthread_suspended(thread_oop)) {
1048       JvmtiVTSuspender::register_vthread_resume(thread_oop);
1049     }
1050   }
1051   return JVMTI_ERROR_NONE;
1052 } /* end SuspendAllVirtualThreads */
1053 
1054 
1055 jvmtiError
1056 JvmtiEnv::ResumeThread(jthread thread) {
1057   JavaThread* java_thread = NULL;
1058   oop thread_oop = NULL;
1059   JvmtiVTMTDisabler vtmt_disabler;
1060   ThreadsListHandle tlh;
1061 
1062   jvmtiError err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1063   if (err != JVMTI_ERROR_NONE) {
1064     return err;
1065   }
1066   err = resume_thread(thread_oop, java_thread, true); // single suspend
1067   return err;
1068 } /* end ResumeThread */
1069 
1070 
1071 // request_count - pre-checked to be greater than or equal to 0
1072 // request_list - pre-checked for NULL
1073 // results - pre-checked for NULL
1074 jvmtiError
1075 JvmtiEnv::ResumeThreadList(jint request_count, const jthread* request_list, jvmtiError* results) {
1076   oop thread_oop = NULL;
1077   JavaThread* java_thread = NULL;
1078   JvmtiVTMTDisabler vtmt_disabler;
1079   ThreadsListHandle tlh;
1080 
1081   for (int i = 0; i < request_count; i++) {
1082     jthread thread = request_list[i];
1083     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1084     if (err != JVMTI_ERROR_NONE) {
1085       if (thread_oop == NULL || err != JVMTI_ERROR_INVALID_THREAD) {
1086         results[i] = err;
1087         continue;
1088       }
1089     }
1090     results[i] = resume_thread(thread_oop, java_thread, true); // single suspend
1091   }
1092   // per-thread resume results returned via results parameter
1093   return JVMTI_ERROR_NONE;
1094 } /* end ResumeThreadList */
1095 
1096 
1097 jvmtiError
1098 JvmtiEnv::ResumeAllVirtualThreads(jint except_count, const jthread* except_list) {
1099   jvmtiError err = JvmtiEnvBase::check_thread_list(except_count, except_list);
1100   if (err != JVMTI_ERROR_NONE) {
1101     return err;
1102   }
1103   if (!JvmtiExport::can_support_virtual_threads()) {
1104     return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
1105   }
1106   ResourceMark rm;
1107   JvmtiVTMTDisabler vtmt_disabler;
1108   GrowableArray<jthread>* elist = new GrowableArray<jthread>(except_count);
1109 
1110   // Collect threads from except_list which suspended status must be restored.
1111   for (int idx = 0; idx < except_count; idx++) {
1112     jthread thread = except_list[idx];
1113     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1114     if (JvmtiVTSuspender::is_vthread_suspended(thread_oop)) {
1115       // is suspended, so its suspended status must be restored
1116       elist->append(except_list[idx]);
1117     }
1118   }
1119 
1120   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *java_thread = jtiwh.next(); ) {
1121     oop vt_oop = java_thread->mounted_vthread();
1122     if (!java_thread->is_exiting() &&
1123         !java_thread->is_jvmti_agent_thread() &&
1124         !java_thread->is_hidden_from_external_view() &&
1125         vt_oop != NULL &&
1126         java_lang_VirtualThread::is_instance(vt_oop) &&
1127         JvmtiEnvBase::is_vthread_alive(vt_oop) &&
1128         JvmtiVTSuspender::is_vthread_suspended(vt_oop) &&
1129         !is_in_thread_list(except_count, except_list, vt_oop)
1130     ) {
1131       resume_thread(vt_oop, java_thread, false); // suspend all
1132     }
1133   }
1134   JvmtiVTSuspender::register_all_vthreads_resume();
1135 
1136   // Restore suspended state for threads from except list that were suspended before.
1137   for (int idx = 0; idx < elist->length(); idx++) {
1138     jthread thread = elist->at(idx);
1139     oop thread_oop = JNIHandles::resolve_external_guard(thread);
1140     if (!JvmtiVTSuspender::is_vthread_suspended(thread_oop)) {
1141       JvmtiVTSuspender::register_vthread_suspend(thread_oop);
1142     }
1143   }
1144   return JVMTI_ERROR_NONE;
1145 } /* end ResumeAllVirtualThreads */
1146 
1147 
1148 // java_thread - protected by ThreadsListHandle and pre-checked
1149 jvmtiError
1150 JvmtiEnv::StopThread(JavaThread* java_thread, jobject exception) {
1151   oop e = JNIHandles::resolve_external_guard(exception);
1152   NULL_CHECK(e, JVMTI_ERROR_NULL_POINTER);
1153 
1154   JavaThread::send_async_exception(java_thread, e);
1155 
1156   return JVMTI_ERROR_NONE;
1157 
1158 } /* end StopThread */
1159 
1160 
1161 jvmtiError
1162 JvmtiEnv::InterruptThread(jthread thread) {
1163   JavaThread* current_thread  = JavaThread::current();
1164   JavaThread* java_thread = NULL;
1165   oop thread_obj = NULL;
1166   HandleMark hm(current_thread);
1167 
1168   JvmtiVTMTDisabler vtmt_disabler;
1169   ThreadsListHandle tlh(current_thread);
1170 
1171   jvmtiError err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
1172   if (err != JVMTI_ERROR_NONE) {
1173     return err;
1174   }
1175 
1176   // Support for virtual threads
1177   if (java_lang_VirtualThread::is_instance(thread_obj)) {
1178     Handle obj(current_thread, thread_obj);
1179     JavaValue result(T_VOID);
1180     JavaCalls::call_virtual(&result,
1181                             obj,
1182                             vmClasses::Thread_klass(),
1183                             vmSymbols::interrupt_method_name(),
1184                             vmSymbols::void_method_signature(),
1185                             current_thread);
1186 
1187     return JVMTI_ERROR_NONE;
1188   }
1189 
1190   // Really this should be a Java call to Thread.interrupt to ensure the same
1191   // semantics, however historically this has not been done for some reason.
1192   // So we continue with that (which means we don't interact with any Java-level
1193   // Interruptible object) but we must set the Java-level interrupted state.
1194   java_lang_Thread::set_interrupted(thread_obj, true);
1195   java_thread->interrupt();
1196 
1197   return JVMTI_ERROR_NONE;
1198 } /* end InterruptThread */
1199 
1200 
1201 // info_ptr - pre-checked for NULL
1202 jvmtiError
1203 JvmtiEnv::GetThreadInfo(jthread thread, jvmtiThreadInfo* info_ptr) {
1204   JavaThread* current_thread = JavaThread::current();
1205   ResourceMark rm(current_thread);
1206   HandleMark hm(current_thread);
1207   JavaThread* java_thread = NULL;
1208   oop thread_oop = NULL;
1209 
1210   ThreadsListHandle tlh(current_thread);
1211 
1212   // if thread is NULL the current thread is used
1213   if (thread == NULL) {
1214     java_thread = JavaThread::current();
1215     thread_oop = get_vthread_or_thread_oop(java_thread);
1216     if (thread_oop == NULL || !thread_oop->is_a(vmClasses::Thread_klass())) {
1217       return JVMTI_ERROR_INVALID_THREAD;
1218     }
1219   } else {
1220     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1221     if (err != JVMTI_ERROR_NONE) {
1222       // We got an error code so we don't have a JavaThread *, but
1223       // only return an error from here if we didn't get a valid
1224       // thread_oop.
1225       // In the virtual thread case the cv_external_thread_to_JavaThread is expected to correctly set
1226       // the thread_oop and return JVMTI_ERROR_INVALID_THREAD which we ignore here.
1227       if (thread_oop == NULL) {
1228         return err;
1229       }
1230     }
1231   }
1232   // We have a valid thread_oop so we can return some thread info.
1233 
1234   Handle thread_obj(current_thread, thread_oop);
1235   Handle name;
1236   ThreadPriority priority;
1237   Handle     thread_group;
1238   Handle context_class_loader;
1239   bool          is_daemon;
1240 
1241   name = Handle(current_thread, java_lang_Thread::name(thread_obj()));
1242 
1243   // Support for virtual threads
1244   if (java_lang_VirtualThread::is_instance(thread_obj())) {
1245     priority = (ThreadPriority)JVMTI_THREAD_NORM_PRIORITY;
1246     is_daemon = true;
1247     if (java_lang_VirtualThread::state(thread_obj()) == java_lang_VirtualThread::TERMINATED) {
1248       thread_group = Handle(current_thread, NULL);
1249     } else {
1250       thread_group = Handle(current_thread, java_lang_Thread_VirtualThreads::get_THREAD_GROUP());
1251     }
1252   } else {
1253     priority = java_lang_Thread::priority(thread_obj());
1254     is_daemon = java_lang_Thread::is_daemon(thread_obj());
1255     if (java_lang_Thread::get_thread_status(thread_obj()) == JavaThreadStatus::TERMINATED) {
1256       thread_group = Handle(current_thread, NULL);
1257     } else {
1258       thread_group = Handle(current_thread, java_lang_Thread::threadGroup(thread_obj()));
1259     }
1260   }
1261 
1262   oop loader = java_lang_Thread::context_class_loader(thread_obj());
1263   if (loader == java_lang_Thread_ClassLoaders::get_NOT_SUPPORTED())
1264     loader = NULL;
1265   context_class_loader = Handle(current_thread, loader);
1266 
1267   { const char *n;
1268 
1269     if (name() != NULL) {
1270       n = java_lang_String::as_utf8_string(name());
1271     } else {
1272       int utf8_length = 0;
1273       n = UNICODE::as_utf8((jchar*) NULL, utf8_length);
1274     }
1275 
1276     info_ptr->name = (char *) jvmtiMalloc(strlen(n)+1);
1277     if (info_ptr->name == NULL)
1278       return JVMTI_ERROR_OUT_OF_MEMORY;
1279 
1280     strcpy(info_ptr->name, n);
1281   }
1282   info_ptr->is_daemon = is_daemon;
1283   info_ptr->priority  = priority;
1284 
1285   info_ptr->context_class_loader = (context_class_loader.is_null()) ? NULL :
1286                                     jni_reference(context_class_loader);
1287   info_ptr->thread_group = jni_reference(thread_group);
1288 
1289   return JVMTI_ERROR_NONE;
1290 } /* end GetThreadInfo */
1291 
1292 
1293 // Threads_lock NOT held
1294 // owned_monitor_count_ptr - pre-checked for NULL
1295 // owned_monitors_ptr - pre-checked for NULL
1296 jvmtiError
1297 JvmtiEnv::GetOwnedMonitorInfo(jthread thread, jint* owned_monitor_count_ptr, jobject** owned_monitors_ptr) {
1298   jvmtiError err = JVMTI_ERROR_NONE;
1299   JavaThread* calling_thread = JavaThread::current();
1300   JavaThread* java_thread = NULL;
1301   HandleMark hm(calling_thread);
1302   oop thread_oop = NULL;
1303 
1304   // growable array of jvmti monitors info on the C-heap
1305   GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list =
1306       new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<jvmtiMonitorStackDepthInfo*>(1, mtServiceability);
1307 
1308 
1309   JvmtiVTMTDisabler vtmt_disabler;
1310   ThreadsListHandle tlh(calling_thread);
1311 
1312   err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1313   if (err != JVMTI_ERROR_NONE) {
1314     return err;
1315   }
1316 
1317   // Support for virtual threads
1318   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1319     // there is no monitor info to collect if target virtual thread is unmounted
1320     if (java_thread != NULL) {
1321       VThreadGetOwnedMonitorInfoClosure op(this,
1322                                            Handle(calling_thread, thread_oop),
1323                                            owned_monitors_list);
1324       Handshake::execute(&op, java_thread);
1325       err = op.result();
1326     }
1327   } else {
1328     EscapeBarrier eb(true, calling_thread, java_thread);
1329     if (!eb.deoptimize_objects(MaxJavaStackTraceDepth)) {
1330       return JVMTI_ERROR_OUT_OF_MEMORY;
1331     }
1332 
1333     if (JvmtiEnvBase::cthread_with_continuation(java_thread)) {
1334       // Carrier thread with a mounted continuation case.
1335       // No contended monitor can be owned by carrier thread in this case.
1336     } else if (java_thread == calling_thread) {
1337       // It is only safe to make a direct call on the current thread.
1338       // All other usage needs to use a direct handshake for safety.
1339       err = get_owned_monitors(calling_thread, java_thread, owned_monitors_list);
1340     } else {
1341       // get owned monitors info with handshake
1342       GetOwnedMonitorInfoClosure op(calling_thread, this, owned_monitors_list);
1343       Handshake::execute(&op, java_thread);
1344       err = op.result();
1345     }
1346   }
1347 
1348   jint owned_monitor_count = owned_monitors_list->length();
1349   if (err == JVMTI_ERROR_NONE) {
1350     if ((err = allocate(owned_monitor_count * sizeof(jobject *),
1351                       (unsigned char**)owned_monitors_ptr)) == JVMTI_ERROR_NONE) {
1352       // copy into the returned array
1353       for (int i = 0; i < owned_monitor_count; i++) {
1354         (*owned_monitors_ptr)[i] =
1355           ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(i))->monitor;
1356       }
1357       *owned_monitor_count_ptr = owned_monitor_count;
1358     }
1359   }
1360   // clean up.
1361   for (int i = 0; i < owned_monitor_count; i++) {
1362     deallocate((unsigned char*)owned_monitors_list->at(i));
1363   }
1364   delete owned_monitors_list;
1365 
1366   return err;
1367 } /* end GetOwnedMonitorInfo */
1368 
1369 
1370 // Threads_lock NOT held
1371 // monitor_info_count_ptr - pre-checked for NULL
1372 // monitor_info_ptr - pre-checked for NULL
1373 jvmtiError
1374 JvmtiEnv::GetOwnedMonitorStackDepthInfo(jthread thread, jint* monitor_info_count_ptr, jvmtiMonitorStackDepthInfo** monitor_info_ptr) {
1375   jvmtiError err = JVMTI_ERROR_NONE;
1376   JavaThread* calling_thread = JavaThread::current();
1377   JavaThread* java_thread = NULL;
1378   HandleMark hm(calling_thread);
1379   oop thread_oop = NULL;
1380 
1381   // growable array of jvmti monitors info on the C-heap
1382   GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list =
1383          new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<jvmtiMonitorStackDepthInfo*>(1, mtServiceability);
1384 
1385   JvmtiVTMTDisabler vtmt_disabler;
1386   ThreadsListHandle tlh(calling_thread);
1387 
1388   err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1389   if (err != JVMTI_ERROR_NONE) {
1390     return err;
1391   }
1392 
1393   // Support for virtual threads
1394   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1395     // there is no monitor info to collect if target virtual thread is unmounted
1396     if (java_thread != NULL) {
1397       VThreadGetOwnedMonitorInfoClosure op(this,
1398                                            Handle(calling_thread, thread_oop),
1399                                            owned_monitors_list);
1400       Handshake::execute(&op, java_thread);
1401       err = op.result();
1402     }
1403   } else {
1404     EscapeBarrier eb(true, calling_thread, java_thread);
1405     if (!eb.deoptimize_objects(MaxJavaStackTraceDepth)) {
1406       return JVMTI_ERROR_OUT_OF_MEMORY;
1407     }
1408 
1409     if (JvmtiEnvBase::cthread_with_continuation(java_thread)) {
1410       // Carrier thread with a mounted continuation case.
1411       // No contended monitor can be owned by carrier thread in this case.
1412     } else if (java_thread == calling_thread) {
1413       // It is only safe to make a direct call on the current thread.
1414       // All other usage needs to use a direct handshake for safety.
1415       err = get_owned_monitors(calling_thread, java_thread, owned_monitors_list);
1416     } else {
1417       // get owned monitors info with handshake
1418       GetOwnedMonitorInfoClosure op(calling_thread, this, owned_monitors_list);
1419       Handshake::execute(&op, java_thread);
1420       err = op.result();
1421     }
1422   }
1423   jint owned_monitor_count = owned_monitors_list->length();
1424   if (err == JVMTI_ERROR_NONE) {
1425     if ((err = allocate(owned_monitor_count * sizeof(jvmtiMonitorStackDepthInfo),
1426                         (unsigned char**)monitor_info_ptr)) == JVMTI_ERROR_NONE) {
1427       // copy to output array.
1428       for (int i = 0; i < owned_monitor_count; i++) {
1429         (*monitor_info_ptr)[i].monitor =
1430           ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(i))->monitor;
1431         (*monitor_info_ptr)[i].stack_depth =
1432           ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(i))->stack_depth;
1433       }
1434     }
1435     *monitor_info_count_ptr = owned_monitor_count;
1436   }
1437 
1438   // clean up.
1439   for (int i = 0; i < owned_monitor_count; i++) {
1440     deallocate((unsigned char*)owned_monitors_list->at(i));
1441   }
1442   delete owned_monitors_list;
1443 
1444   return err;
1445 } /* end GetOwnedMonitorStackDepthInfo */
1446 
1447 
1448 // Threads_lock NOT held
1449 // monitor_ptr - pre-checked for NULL
1450 jvmtiError
1451 JvmtiEnv::GetCurrentContendedMonitor(jthread thread, jobject* monitor_ptr) {
1452   jvmtiError err = JVMTI_ERROR_NONE;
1453   JavaThread* calling_thread = JavaThread::current();
1454   JavaThread* java_thread = NULL;
1455   HandleMark hm(calling_thread);
1456   oop thread_oop = NULL;
1457 
1458   JvmtiVTMTDisabler vtmt_disabler;
1459   ThreadsListHandle tlh(calling_thread);
1460 
1461   err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1462   if (err != JVMTI_ERROR_NONE) {
1463     return err;
1464   }
1465 
1466   // Support for virtual threads
1467   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1468     // there is no monitor info to collect if target virtual thread is unmounted
1469     if (java_thread != NULL) {
1470       VThreadGetCurrentContendedMonitorClosure op(this,
1471                                                   Handle(calling_thread, thread_oop),
1472                                                   monitor_ptr);
1473       Handshake::execute(&op, java_thread);
1474       err = op.result();
1475     } else {
1476       *monitor_ptr = NULL;
1477       if (!JvmtiEnvBase::is_vthread_alive(thread_oop)) {
1478         err = JVMTI_ERROR_THREAD_NOT_ALIVE;
1479       }
1480     }
1481     return err;
1482   }
1483   if (JvmtiEnvBase::cthread_with_continuation(java_thread)) {
1484     // Carrier thread with a mounted continuation case.
1485     // No contended monitor can be owned by carrier thread in this case.
1486     *monitor_ptr = NULL;
1487   } else if (java_thread == calling_thread) {
1488     // It is only safe to make a direct call on the current thread.
1489     // All other usage needs to use a direct handshake for safety.
1490     err = get_current_contended_monitor(calling_thread, java_thread, monitor_ptr);
1491   } else {
1492     // get contended monitor information with handshake
1493     GetCurrentContendedMonitorClosure op(calling_thread, this, monitor_ptr);
1494     Handshake::execute(&op, java_thread);
1495     err = op.result();
1496   }
1497   return err;
1498 } /* end GetCurrentContendedMonitor */
1499 
1500 
1501 // proc - pre-checked for NULL
1502 // arg - NULL is a valid value, must be checked
1503 jvmtiError
1504 JvmtiEnv::RunAgentThread(jthread thread, jvmtiStartFunction proc, const void* arg, jint priority) {
1505   JavaThread* current_thread = JavaThread::current();
1506 
1507   JavaThread* java_thread = NULL;
1508   oop thread_oop = NULL;
1509   ThreadsListHandle tlh(current_thread);
1510   jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1511   if (err != JVMTI_ERROR_NONE) {
1512     // We got an error code so we don't have a JavaThread *, but
1513     // only return an error from here if we didn't get a valid
1514     // thread_oop.
1515     if (thread_oop == NULL) {
1516       return err;
1517     }
1518     // We have a valid thread_oop.
1519   }
1520 
1521   if (java_thread != NULL) {
1522     // 'thread' refers to an existing JavaThread.
1523     return JVMTI_ERROR_INVALID_THREAD;
1524   }
1525   if (java_lang_VirtualThread::is_instance(thread_oop)) {
1526     return JVMTI_ERROR_INVALID_THREAD;
1527   }
1528 
1529   if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
1530     return JVMTI_ERROR_INVALID_PRIORITY;
1531   }
1532 
1533   Handle thread_hndl(current_thread, thread_oop);
1534 
1535   JvmtiAgentThread* new_thread = new JvmtiAgentThread(this, proc, arg);
1536 
1537   // At this point it may be possible that no osthread was created for the
1538   // JavaThread due to lack of resources.
1539   if (new_thread->osthread() == NULL) {
1540     // The new thread is not known to Thread-SMR yet so we can just delete.
1541     delete new_thread;
1542     return JVMTI_ERROR_OUT_OF_MEMORY;
1543   }
1544 
1545   JavaThread::start_internal_daemon(current_thread, new_thread, thread_hndl,
1546                                     (ThreadPriority)priority);
1547 
1548   return JVMTI_ERROR_NONE;
1549 } /* end RunAgentThread */
1550 
1551   //
1552   // Thread Group functions
1553   //
1554 
1555 // group_count_ptr - pre-checked for NULL
1556 // groups_ptr - pre-checked for NULL
1557 jvmtiError
1558 JvmtiEnv::GetTopThreadGroups(jint* group_count_ptr, jthreadGroup** groups_ptr) {
1559   JavaThread* current_thread = JavaThread::current();
1560 
1561   // Only one top level thread group now.
1562   *group_count_ptr = 1;
1563 
1564   // Allocate memory to store global-refs to the thread groups.
1565   // Assume this area is freed by caller.
1566   *groups_ptr = (jthreadGroup *) jvmtiMalloc((sizeof(jthreadGroup)) * (*group_count_ptr));
1567 
1568   NULL_CHECK(*groups_ptr, JVMTI_ERROR_OUT_OF_MEMORY);
1569 
1570   // Convert oop to Handle, then convert Handle to global-ref.
1571   {
1572     HandleMark hm(current_thread);
1573     Handle system_thread_group(current_thread, Universe::system_thread_group());
1574     *groups_ptr[0] = jni_reference(system_thread_group);
1575   }
1576 
1577   return JVMTI_ERROR_NONE;
1578 } /* end GetTopThreadGroups */
1579 
1580 
1581 // info_ptr - pre-checked for NULL
1582 jvmtiError
1583 JvmtiEnv::GetThreadGroupInfo(jthreadGroup group, jvmtiThreadGroupInfo* info_ptr) {
1584   Thread* current_thread = Thread::current();
1585   ResourceMark rm(current_thread);
1586   HandleMark hm(current_thread);
1587 
1588   Handle group_obj (current_thread, JNIHandles::resolve_external_guard(group));
1589   NULL_CHECK(group_obj(), JVMTI_ERROR_INVALID_THREAD_GROUP);
1590 
1591   const char* name;
1592   Handle parent_group;
1593   ThreadPriority max_priority;
1594 
1595   name         = java_lang_ThreadGroup::name(group_obj());
1596   parent_group = Handle(current_thread, java_lang_ThreadGroup::parent(group_obj()));
1597   max_priority = java_lang_ThreadGroup::maxPriority(group_obj());
1598 
1599   if (name != NULL) {
1600     info_ptr->name = (char*)jvmtiMalloc(strlen(name)+1);
1601     NULL_CHECK(info_ptr->name, JVMTI_ERROR_OUT_OF_MEMORY);
1602     strcpy(info_ptr->name, name);
1603   } else {
1604     info_ptr->name = NULL;
1605   }
1606 
1607   info_ptr->parent       = jni_reference(parent_group);
1608   info_ptr->max_priority = max_priority;
1609   info_ptr->is_daemon    = JNI_FALSE;
1610 
1611   return JVMTI_ERROR_NONE;
1612 } /* end GetThreadGroupInfo */
1613 
1614 // thread_count_ptr - pre-checked for NULL
1615 // threads_ptr - pre-checked for NULL
1616 // group_count_ptr - pre-checked for NULL
1617 // groups_ptr - pre-checked for NULL
1618 jvmtiError
1619 JvmtiEnv::GetThreadGroupChildren(jthreadGroup group, jint* thread_count_ptr, jthread** threads_ptr, jint* group_count_ptr, jthreadGroup** groups_ptr) {
1620   JavaThread* current_thread = JavaThread::current();
1621   oop group_obj = JNIHandles::resolve_external_guard(group);
1622   NULL_CHECK(group_obj, JVMTI_ERROR_INVALID_THREAD_GROUP);
1623 
1624   Handle *thread_objs = NULL;
1625   Handle *group_objs  = NULL;
1626   int nthreads = 0;
1627   int ngroups = 0;
1628   int hidden_threads = 0;
1629 
1630   ResourceMark rm(current_thread);
1631   HandleMark hm(current_thread);
1632 
1633   Handle group_hdl(current_thread, group_obj);
1634 
1635   nthreads = get_live_threads(current_thread, group_hdl, &thread_objs);
1636   ngroups = get_subgroups(current_thread, group_hdl, &group_objs);
1637 
1638   *group_count_ptr  = ngroups;
1639   *thread_count_ptr = nthreads;
1640   *threads_ptr     = new_jthreadArray(nthreads, thread_objs);
1641   *groups_ptr      = new_jthreadGroupArray(ngroups, group_objs);
1642   if ((nthreads > 0) && (*threads_ptr == NULL)) {
1643     return JVMTI_ERROR_OUT_OF_MEMORY;
1644   }
1645   if ((ngroups > 0) && (*groups_ptr == NULL)) {
1646     return JVMTI_ERROR_OUT_OF_MEMORY;
1647   }
1648 
1649   return JVMTI_ERROR_NONE;
1650 } /* end GetThreadGroupChildren */
1651 
1652 
1653   //
1654   // Stack Frame functions
1655   //
1656 
1657 // Threads_lock NOT held
1658 // max_frame_count - pre-checked to be greater than or equal to 0
1659 // frame_buffer - pre-checked for NULL
1660 // count_ptr - pre-checked for NULL
1661 jvmtiError
1662 JvmtiEnv::GetStackTrace(jthread thread, jint start_depth, jint max_frame_count, jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1663   jvmtiError err = JVMTI_ERROR_NONE;
1664   JavaThread* java_thread = NULL;
1665   JavaThread* current_thread = JavaThread::current();
1666   HandleMark hm(current_thread);
1667   oop thread_obj = NULL;
1668 
1669   JvmtiVTMTDisabler vtmt_disabler;
1670   ThreadsListHandle tlh(current_thread);
1671 
1672   err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
1673   if (err != JVMTI_ERROR_NONE) {
1674     return err;
1675   }
1676 
1677   // Support for virtual threads
1678   if (java_lang_VirtualThread::is_instance(thread_obj)) {
1679     if (java_thread == NULL) { // target virtual thread is unmounted
1680       ResourceMark rm(current_thread);
1681 
1682       VM_VThreadGetStackTrace op(this, Handle(current_thread, thread_obj),
1683                                  start_depth, max_frame_count,
1684                                  frame_buffer, count_ptr);
1685       VMThread::execute(&op);
1686       return op.result();
1687     }
1688     VThreadGetStackTraceClosure op(this, Handle(current_thread, thread_obj),
1689                                    start_depth, max_frame_count, frame_buffer, count_ptr);
1690     Handshake::execute(&op, java_thread);
1691     return op.result();
1692   }
1693 
1694   // It is only safe to perform the direct operation on the current
1695   // thread. All other usage needs to use a direct handshake for safety.
1696   if (java_thread == JavaThread::current()) {
1697     err = get_stack_trace(java_thread, start_depth, max_frame_count, frame_buffer, count_ptr);
1698   } else {
1699     // Get stack trace with handshake.
1700     GetStackTraceClosure op(this, start_depth, max_frame_count, frame_buffer, count_ptr);
1701     Handshake::execute(&op, java_thread);
1702     err = op.result();
1703   }
1704 
1705   return err;
1706 } /* end GetStackTrace */
1707 
1708 
1709 // max_frame_count - pre-checked to be greater than or equal to 0
1710 // stack_info_ptr - pre-checked for NULL
1711 // thread_count_ptr - pre-checked for NULL
1712 jvmtiError
1713 JvmtiEnv::GetAllStackTraces(jint max_frame_count, jvmtiStackInfo** stack_info_ptr, jint* thread_count_ptr) {
1714   jvmtiError err = JVMTI_ERROR_NONE;
1715   JavaThread* calling_thread = JavaThread::current();
1716 
1717   // JVMTI get stack traces at safepoint.
1718   VM_GetAllStackTraces op(this, calling_thread, max_frame_count);
1719   VMThread::execute(&op);
1720   *thread_count_ptr = op.final_thread_count();
1721   *stack_info_ptr = op.stack_info();
1722   err = op.result();
1723   return err;
1724 } /* end GetAllStackTraces */
1725 
1726 
1727 // thread_count - pre-checked to be greater than or equal to 0
1728 // thread_list - pre-checked for NULL
1729 // max_frame_count - pre-checked to be greater than or equal to 0
1730 // stack_info_ptr - pre-checked for NULL
1731 jvmtiError
1732 JvmtiEnv::GetThreadListStackTraces(jint thread_count, const jthread* thread_list, jint max_frame_count, jvmtiStackInfo** stack_info_ptr) {
1733   jvmtiError err = JVMTI_ERROR_NONE;
1734 
1735   if (thread_count == 1) {
1736     JvmtiVTMTDisabler vtmt_disabler;
1737 
1738     // Use direct handshake if we need to get only one stack trace.
1739     JavaThread *current_thread = JavaThread::current();
1740     ThreadsListHandle tlh(current_thread);
1741     jthread thread = thread_list[0];
1742     JavaThread *java_thread;
1743     oop thread_obj = NULL;
1744     err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
1745     if (err != JVMTI_ERROR_NONE) {
1746       return err;
1747     }
1748 
1749     // Support for virtual threads
1750     if (java_lang_VirtualThread::is_instance(thread_obj)) {
1751       if (java_thread == NULL) { // target virtual thread is unmounted
1752         ResourceMark rm(current_thread);
1753         MultipleStackTracesCollector collector(this, max_frame_count);
1754         collector.fill_frames(thread, java_thread, thread_obj);
1755         collector.allocate_and_fill_stacks(1);
1756         *stack_info_ptr = collector.stack_info();
1757         return collector.result();
1758       }
1759     }
1760 
1761     GetSingleStackTraceClosure op(this, current_thread, thread, max_frame_count);
1762     Handshake::execute(&op, java_thread);
1763     err = op.result();
1764     if (err == JVMTI_ERROR_NONE) {
1765       *stack_info_ptr = op.stack_info();
1766     }
1767   } else {
1768     // JVMTI get stack traces at safepoint.
1769     VM_GetThreadListStackTraces op(this, thread_count, thread_list, max_frame_count);
1770     VMThread::execute(&op);
1771     err = op.result();
1772     if (err == JVMTI_ERROR_NONE) {
1773       *stack_info_ptr = op.stack_info();
1774     }
1775   }
1776   return err;
1777 } /* end GetThreadListStackTraces */
1778 
1779 
1780 // Threads_lock NOT held
1781 // count_ptr - pre-checked for NULL
1782 jvmtiError
1783 JvmtiEnv::GetFrameCount(jthread thread, jint* count_ptr) {
1784   jvmtiError err = JVMTI_ERROR_NONE;
1785   JavaThread* java_thread = NULL;
1786   JavaThread* current_thread = JavaThread::current();
1787   HandleMark hm(current_thread);
1788   oop thread_obj = NULL;
1789 
1790   JvmtiVTMTDisabler vtmt_disabler;
1791   ThreadsListHandle tlh(current_thread);
1792 
1793   err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
1794   if (err != JVMTI_ERROR_NONE) {
1795     return err;
1796   }
1797 
1798   // Support for virtual threads
1799   if (java_lang_VirtualThread::is_instance(thread_obj)) {
1800     if (java_thread == NULL) { // target virtual thread is unmounted
1801       VM_VThreadGetFrameCount op(this, Handle(current_thread, thread_obj),  count_ptr);
1802       VMThread::execute(&op);
1803       return op.result();
1804     }
1805     VThreadGetFrameCountClosure op(this, Handle(current_thread, thread_obj), count_ptr);
1806     Handshake::execute(&op, java_thread);
1807     return op.result();
1808   }
1809 
1810   // It is only safe to perform the direct operation on the current
1811   // thread. All other usage needs to use a direct handshake for safety.
1812   if (java_thread == JavaThread::current()) {
1813     err = get_frame_count(java_thread, count_ptr);
1814   } else {
1815     // get java stack frame count with handshake.
1816     GetFrameCountClosure op(this, count_ptr);
1817     Handshake::execute(&op, java_thread);
1818     err = op.result();
1819   }
1820   return err;
1821 } /* end GetFrameCount */
1822 
1823 
1824 // java_thread - protected by ThreadsListHandle and pre-checked
1825 jvmtiError
1826 JvmtiEnv::PopFrame(JavaThread* java_thread) {
1827   // retrieve or create the state
1828   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1829   if (state == NULL) {
1830     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1831   }
1832 
1833   // Eagerly reallocate scalar replaced objects.
1834   JavaThread* current_thread = JavaThread::current();
1835   EscapeBarrier eb(true, current_thread, java_thread);
1836   if (!eb.deoptimize_objects(1)) {
1837     // Reallocation of scalar replaced objects failed -> return with error
1838     return JVMTI_ERROR_OUT_OF_MEMORY;
1839   }
1840 
1841   MutexLocker mu(JvmtiThreadState_lock);
1842   UpdateForPopTopFrameClosure op(state);
1843   if (java_thread == current_thread) {
1844     op.doit(java_thread, true /* self */);
1845   } else {
1846     Handshake::execute(&op, java_thread);
1847   }
1848   return op.result();
1849 } /* end PopFrame */
1850 
1851 
1852 // Threads_lock NOT held
1853 // depth - pre-checked as non-negative
1854 // method_ptr - pre-checked for NULL
1855 // location_ptr - pre-checked for NULL
1856 jvmtiError
1857 JvmtiEnv::GetFrameLocation(jthread thread, jint depth, jmethodID* method_ptr, jlocation* location_ptr) {
1858   jvmtiError err = JVMTI_ERROR_NONE;
1859   JavaThread* java_thread = NULL;
1860   JavaThread* current_thread = JavaThread::current();
1861   HandleMark hm(current_thread);
1862   oop thread_obj = NULL;
1863 
1864   JvmtiVTMTDisabler vtmt_disabler;
1865   ThreadsListHandle tlh(current_thread);
1866 
1867   err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
1868   if (err != JVMTI_ERROR_NONE) {
1869     return err;
1870   }
1871 
1872   // Support for virtual threads
1873   if (java_lang_VirtualThread::is_instance(thread_obj)) {
1874     if (java_thread == NULL) { // target virtual thread is unmounted
1875       err = get_frame_location(thread_obj, depth, method_ptr, location_ptr);
1876       return err;
1877     }
1878     VThreadGetFrameLocationClosure op(this, Handle(current_thread, thread_obj),
1879                                       depth, method_ptr, location_ptr);
1880     Handshake::execute(&op, java_thread);
1881     return op.result();
1882   }
1883 
1884   // It is only safe to perform the direct operation on the current
1885   // thread. All other usage needs to use a direct handshake for safety.
1886   if (java_thread == JavaThread::current()) {
1887     err = get_frame_location(java_thread, depth, method_ptr, location_ptr);
1888   } else {
1889     // JVMTI get java stack frame location via direct handshake.
1890     GetFrameLocationClosure op(this, depth, method_ptr, location_ptr);
1891     Handshake::execute(&op, java_thread);
1892     err = op.result();
1893   }
1894   return err;
1895 } /* end GetFrameLocation */
1896 
1897 
1898 // Threads_lock NOT held, java_thread not protected by lock
1899 // depth - pre-checked as non-negative
1900 jvmtiError
1901 JvmtiEnv::NotifyFramePop(jthread thread, jint depth) {
1902   jvmtiError err = JVMTI_ERROR_NONE;
1903   ResourceMark rm;
1904   JavaThread* java_thread = NULL;
1905   oop thread_obj = NULL;
1906   JvmtiVTMTDisabler vtmt_disabler;
1907   ThreadsListHandle tlh;
1908 
1909   err = get_threadOop_and_JavaThread(tlh.list(), thread, &java_thread, &thread_obj);
1910   if (err != JVMTI_ERROR_NONE) {
1911     return err;
1912   }
1913 
1914   JavaThread* current = JavaThread::current();
1915   HandleMark hm(current);
1916   Handle thread_handle(current, thread_obj);
1917 
1918   // Support for virtual threads
1919   if (java_lang_VirtualThread::is_instance(thread_obj)) {
1920     if (java_thread == NULL) {
1921       // java_thread is NULL if virtual thread is unmounted
1922       JvmtiThreadState *state = JvmtiThreadState::state_for(java_thread, thread_handle);
1923       if (state == NULL) {
1924         return JVMTI_ERROR_THREAD_NOT_ALIVE;
1925       }
1926       MutexLocker mu(JvmtiThreadState_lock);
1927       int frame_number = state->count_frames() - depth;
1928       state->env_thread_state(this)->set_frame_pop(frame_number);
1929       return JVMTI_ERROR_NONE;
1930     }
1931   }
1932 
1933   JvmtiThreadState *state = JvmtiThreadState::state_for(java_thread, thread_handle);
1934   if (state == NULL) {
1935     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1936   }
1937 
1938   SetFramePopClosure op(this, state, depth);
1939   MutexLocker mu(current, JvmtiThreadState_lock);
1940   if (java_thread == current) {
1941     op.doit(java_thread, true /* self */);
1942   } else {
1943     Handshake::execute(&op, java_thread);
1944   }
1945   return op.result();
1946 } /* end NotifyFramePop */
1947 
1948 
1949   //
1950   // Force Early Return functions
1951   //
1952 
1953 // java_thread - protected by ThreadsListHandle and pre-checked
1954 jvmtiError
1955 JvmtiEnv::ForceEarlyReturnObject(JavaThread* java_thread, jobject value) {
1956   jvalue val;
1957   val.l = value;
1958   return force_early_return(java_thread, val, atos);
1959 } /* end ForceEarlyReturnObject */
1960 
1961 
1962 // java_thread - protected by ThreadsListHandle and pre-checked
1963 jvmtiError
1964 JvmtiEnv::ForceEarlyReturnInt(JavaThread* java_thread, jint value) {
1965   jvalue val;
1966   val.i = value;
1967   return force_early_return(java_thread, val, itos);
1968 } /* end ForceEarlyReturnInt */
1969 
1970 
1971 // java_thread - protected by ThreadsListHandle and pre-checked
1972 jvmtiError
1973 JvmtiEnv::ForceEarlyReturnLong(JavaThread* java_thread, jlong value) {
1974   jvalue val;
1975   val.j = value;
1976   return force_early_return(java_thread, val, ltos);
1977 } /* end ForceEarlyReturnLong */
1978 
1979 
1980 // java_thread - protected by ThreadsListHandle and pre-checked
1981 jvmtiError
1982 JvmtiEnv::ForceEarlyReturnFloat(JavaThread* java_thread, jfloat value) {
1983   jvalue val;
1984   val.f = value;
1985   return force_early_return(java_thread, val, ftos);
1986 } /* end ForceEarlyReturnFloat */
1987 
1988 
1989 // java_thread - protected by ThreadsListHandle and pre-checked
1990 jvmtiError
1991 JvmtiEnv::ForceEarlyReturnDouble(JavaThread* java_thread, jdouble value) {
1992   jvalue val;
1993   val.d = value;
1994   return force_early_return(java_thread, val, dtos);
1995 } /* end ForceEarlyReturnDouble */
1996 
1997 
1998 // java_thread - protected by ThreadsListHandle and pre-checked
1999 jvmtiError
2000 JvmtiEnv::ForceEarlyReturnVoid(JavaThread* java_thread) {
2001   jvalue val;
2002   val.j = 0L;
2003   return force_early_return(java_thread, val, vtos);
2004 } /* end ForceEarlyReturnVoid */
2005 
2006 
2007   //
2008   // Heap functions
2009   //
2010 
2011 // klass - NULL is a valid value, must be checked
2012 // initial_object - NULL is a valid value, must be checked
2013 // callbacks - pre-checked for NULL
2014 // user_data - NULL is a valid value, must be checked
2015 jvmtiError
2016 JvmtiEnv::FollowReferences(jint heap_filter, jclass klass, jobject initial_object, const jvmtiHeapCallbacks* callbacks, const void* user_data) {
2017   // check klass if provided
2018   Klass* k = NULL;
2019   if (klass != NULL) {
2020     oop k_mirror = JNIHandles::resolve_external_guard(klass);
2021     if (k_mirror == NULL) {
2022       return JVMTI_ERROR_INVALID_CLASS;
2023     }
2024     if (java_lang_Class::is_primitive(k_mirror)) {
2025       return JVMTI_ERROR_NONE;
2026     }
2027     k = java_lang_Class::as_Klass(k_mirror);
2028     if (klass == NULL) {
2029       return JVMTI_ERROR_INVALID_CLASS;
2030     }
2031   }
2032 
2033   if (initial_object != NULL) {
2034     oop init_obj = JNIHandles::resolve_external_guard(initial_object);
2035     if (init_obj == NULL) {
2036       return JVMTI_ERROR_INVALID_OBJECT;
2037     }
2038   }
2039 
2040   Thread *thread = Thread::current();
2041   HandleMark hm(thread);
2042 
2043   TraceTime t("FollowReferences", TRACETIME_LOG(Debug, jvmti, objecttagging));
2044   JvmtiTagMap::tag_map_for(this)->follow_references(heap_filter, k, initial_object, callbacks, user_data);
2045   return JVMTI_ERROR_NONE;
2046 } /* end FollowReferences */
2047 
2048 
2049 // klass - NULL is a valid value, must be checked
2050 // callbacks - pre-checked for NULL
2051 // user_data - NULL is a valid value, must be checked
2052 jvmtiError
2053 JvmtiEnv::IterateThroughHeap(jint heap_filter, jclass klass, const jvmtiHeapCallbacks* callbacks, const void* user_data) {
2054   // check klass if provided
2055   Klass* k = NULL;
2056   if (klass != NULL) {
2057     oop k_mirror = JNIHandles::resolve_external_guard(klass);
2058     if (k_mirror == NULL) {
2059       return JVMTI_ERROR_INVALID_CLASS;
2060     }
2061     if (java_lang_Class::is_primitive(k_mirror)) {
2062       return JVMTI_ERROR_NONE;
2063     }
2064     k = java_lang_Class::as_Klass(k_mirror);
2065     if (k == NULL) {
2066       return JVMTI_ERROR_INVALID_CLASS;
2067     }
2068   }
2069 
2070   TraceTime t("IterateThroughHeap", TRACETIME_LOG(Debug, jvmti, objecttagging));
2071   JvmtiTagMap::tag_map_for(this)->iterate_through_heap(heap_filter, k, callbacks, user_data);
2072   return JVMTI_ERROR_NONE;
2073 } /* end IterateThroughHeap */
2074 
2075 
2076 // tag_ptr - pre-checked for NULL
2077 jvmtiError
2078 JvmtiEnv::GetTag(jobject object, jlong* tag_ptr) {
2079   oop o = JNIHandles::resolve_external_guard(object);
2080   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
2081   *tag_ptr = JvmtiTagMap::tag_map_for(this)->get_tag(object);
2082   return JVMTI_ERROR_NONE;
2083 } /* end GetTag */
2084 
2085 
2086 jvmtiError
2087 JvmtiEnv::SetTag(jobject object, jlong tag) {
2088   oop o = JNIHandles::resolve_external_guard(object);
2089   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
2090   JvmtiTagMap::tag_map_for(this)->set_tag(object, tag);
2091   return JVMTI_ERROR_NONE;
2092 } /* end SetTag */
2093 
2094 
2095 // tag_count - pre-checked to be greater than or equal to 0
2096 // tags - pre-checked for NULL
2097 // count_ptr - pre-checked for NULL
2098 // object_result_ptr - NULL is a valid value, must be checked
2099 // tag_result_ptr - NULL is a valid value, must be checked
2100 jvmtiError
2101 JvmtiEnv::GetObjectsWithTags(jint tag_count, const jlong* tags, jint* count_ptr, jobject** object_result_ptr, jlong** tag_result_ptr) {
2102   TraceTime t("GetObjectsWithTags", TRACETIME_LOG(Debug, jvmti, objecttagging));
2103   return JvmtiTagMap::tag_map_for(this)->get_objects_with_tags((jlong*)tags, tag_count, count_ptr, object_result_ptr, tag_result_ptr);
2104 } /* end GetObjectsWithTags */
2105 
2106 
2107 jvmtiError
2108 JvmtiEnv::ForceGarbageCollection() {
2109   Universe::heap()->collect(GCCause::_jvmti_force_gc);
2110   return JVMTI_ERROR_NONE;
2111 } /* end ForceGarbageCollection */
2112 
2113 
2114   //
2115   // Heap (1.0) functions
2116   //
2117 
2118 // object_reference_callback - pre-checked for NULL
2119 // user_data - NULL is a valid value, must be checked
2120 jvmtiError
2121 JvmtiEnv::IterateOverObjectsReachableFromObject(jobject object, jvmtiObjectReferenceCallback object_reference_callback, const void* user_data) {
2122   oop o = JNIHandles::resolve_external_guard(object);
2123   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
2124   JvmtiTagMap::tag_map_for(this)->iterate_over_objects_reachable_from_object(object, object_reference_callback, user_data);
2125   return JVMTI_ERROR_NONE;
2126 } /* end IterateOverObjectsReachableFromObject */
2127 
2128 
2129 // heap_root_callback - NULL is a valid value, must be checked
2130 // stack_ref_callback - NULL is a valid value, must be checked
2131 // object_ref_callback - NULL is a valid value, must be checked
2132 // user_data - NULL is a valid value, must be checked
2133 jvmtiError
2134 JvmtiEnv::IterateOverReachableObjects(jvmtiHeapRootCallback heap_root_callback, jvmtiStackReferenceCallback stack_ref_callback, jvmtiObjectReferenceCallback object_ref_callback, const void* user_data) {
2135   TraceTime t("IterateOverReachableObjects", TRACETIME_LOG(Debug, jvmti, objecttagging));
2136   JvmtiTagMap::tag_map_for(this)->iterate_over_reachable_objects(heap_root_callback, stack_ref_callback, object_ref_callback, user_data);
2137   return JVMTI_ERROR_NONE;
2138 } /* end IterateOverReachableObjects */
2139 
2140 
2141 // heap_object_callback - pre-checked for NULL
2142 // user_data - NULL is a valid value, must be checked
2143 jvmtiError
2144 JvmtiEnv::IterateOverHeap(jvmtiHeapObjectFilter object_filter, jvmtiHeapObjectCallback heap_object_callback, const void* user_data) {
2145   TraceTime t("IterateOverHeap", TRACETIME_LOG(Debug, jvmti, objecttagging));
2146   Thread *thread = Thread::current();
2147   HandleMark hm(thread);
2148   JvmtiTagMap::tag_map_for(this)->iterate_over_heap(object_filter, NULL, heap_object_callback, user_data);
2149   return JVMTI_ERROR_NONE;
2150 } /* end IterateOverHeap */
2151 
2152 
2153 // k_mirror - may be primitive, this must be checked
2154 // heap_object_callback - pre-checked for NULL
2155 // user_data - NULL is a valid value, must be checked
2156 jvmtiError
2157 JvmtiEnv::IterateOverInstancesOfClass(oop k_mirror, jvmtiHeapObjectFilter object_filter, jvmtiHeapObjectCallback heap_object_callback, const void* user_data) {
2158   if (java_lang_Class::is_primitive(k_mirror)) {
2159     // DO PRIMITIVE CLASS PROCESSING
2160     return JVMTI_ERROR_NONE;
2161   }
2162   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2163   if (klass == NULL) {
2164     return JVMTI_ERROR_INVALID_CLASS;
2165   }
2166   TraceTime t("IterateOverInstancesOfClass", TRACETIME_LOG(Debug, jvmti, objecttagging));
2167   JvmtiTagMap::tag_map_for(this)->iterate_over_heap(object_filter, klass, heap_object_callback, user_data);
2168   return JVMTI_ERROR_NONE;
2169 } /* end IterateOverInstancesOfClass */
2170 
2171 
2172   //
2173   // Local Variable functions
2174   //
2175 
2176 // Threads_lock NOT held
2177 // depth - pre-checked as non-negative
2178 // value_ptr - pre-checked for NULL
2179 jvmtiError
2180 JvmtiEnv::GetLocalObject(jthread thread, jint depth, jint slot, jobject* value_ptr) {
2181   jvmtiError err = JVMTI_ERROR_NONE;
2182   JavaThread* java_thread = NULL;
2183   JavaThread* current_thread = JavaThread::current();
2184   // rm object is created to clean up the javaVFrame created in
2185   // doit_prologue(), but after doit() is finished with it.
2186   ResourceMark rm(current_thread);
2187   HandleMark hm(current_thread);
2188   oop thread_obj = JNIHandles::resolve_external_guard(thread);
2189 
2190   if (java_lang_VirtualThread::is_instance(thread_obj)) {
2191     // Support for virtual threads
2192     VM_VirtualThreadGetOrSetLocal op(this, Handle(current_thread, thread_obj),
2193                                    current_thread, depth, slot);
2194     VMThread::execute(&op);
2195     err = op.result();
2196     if (err == JVMTI_ERROR_NONE) {
2197       *value_ptr = op.value().l;
2198     }
2199   } else {
2200     // Support for ordinary threads
2201     ThreadsListHandle tlh(current_thread);
2202     err = get_JavaThread(tlh.list(), thread, &java_thread);
2203     if (err != JVMTI_ERROR_NONE) {
2204       return err;
2205     }
2206     VM_GetOrSetLocal op(java_thread, current_thread, depth, slot);
2207     VMThread::execute(&op);
2208     err = op.result();
2209     if (err == JVMTI_ERROR_NONE) {
2210       *value_ptr = op.value().l;
2211     }
2212   }
2213   return err;
2214 } /* end GetLocalObject */
2215 
2216 // Threads_lock NOT held
2217 // depth - pre-checked as non-negative
2218 // value - pre-checked for NULL
2219 jvmtiError
2220 JvmtiEnv::GetLocalInstance(jthread thread, jint depth, jobject* value_ptr){
2221   jvmtiError err = JVMTI_ERROR_NONE;
2222   JavaThread* java_thread = NULL;
2223   JavaThread* current_thread = JavaThread::current();
2224   // rm object is created to clean up the javaVFrame created in
2225   // doit_prologue(), but after doit() is finished with it.
2226   ResourceMark rm(current_thread);
2227   HandleMark hm(current_thread);
2228   oop thread_obj = JNIHandles::resolve_external_guard(thread);
2229 
2230   if (java_lang_VirtualThread::is_instance(thread_obj)) {
2231     // Support for virtual threads
2232     VM_VirtualThreadGetReceiver op(this, Handle(current_thread, thread_obj),
2233                                  current_thread, depth);
2234     VMThread::execute(&op);
2235     err = op.result();
2236     if (err == JVMTI_ERROR_NONE) {
2237       *value_ptr = op.value().l;
2238     }
2239   } else {
2240     // Support for ordinary threads
2241     ThreadsListHandle tlh(current_thread);
2242     err = get_JavaThread(tlh.list(), thread, &java_thread);
2243     if (err != JVMTI_ERROR_NONE) {
2244       return err;
2245     }
2246     VM_GetReceiver op(java_thread, current_thread, depth);
2247     VMThread::execute(&op);
2248     err = op.result();
2249     if (err == JVMTI_ERROR_NONE) {
2250       *value_ptr = op.value().l;
2251     }
2252   }
2253   return err;
2254 } /* end GetLocalInstance */
2255 
2256 
2257 // Threads_lock NOT held
2258 // depth - pre-checked as non-negative
2259 // value_ptr - pre-checked for NULL
2260 jvmtiError
2261 JvmtiEnv::GetLocalInt(jthread thread, jint depth, jint slot, jint* value_ptr) {
2262   jvmtiError err = JVMTI_ERROR_NONE;
2263   JavaThread* java_thread = NULL;
2264   JavaThread* current_thread = JavaThread::current();
2265   // rm object is created to clean up the javaVFrame created in
2266   // doit_prologue(), but after doit() is finished with it.
2267   ResourceMark rm(current_thread);
2268   HandleMark hm(current_thread);
2269   oop thread_obj = JNIHandles::resolve_external_guard(thread);
2270 
2271   if (java_lang_VirtualThread::is_instance(thread_obj)) {
2272     // Support for virtual threads
2273     VM_VirtualThreadGetOrSetLocal op(this, Handle(current_thread, thread_obj),
2274                                    depth, slot, T_INT);
2275     VMThread::execute(&op);
2276     err = op.result();
2277     if (err == JVMTI_ERROR_NONE) {
2278       *value_ptr = op.value().i;
2279     }
2280   } else {
2281     // Support for ordinary threads
2282     ThreadsListHandle tlh(current_thread);
2283     err = get_JavaThread(tlh.list(), thread, &java_thread);
2284     if (err != JVMTI_ERROR_NONE) {
2285       return err;
2286     }
2287     VM_GetOrSetLocal op(java_thread, depth, slot, T_INT);
2288     VMThread::execute(&op);
2289     err = op.result();
2290     if (err == JVMTI_ERROR_NONE) {
2291       *value_ptr = op.value().i;
2292     }
2293   }
2294   return err;
2295 } /* end GetLocalInt */
2296 
2297 
2298 // Threads_lock NOT held
2299 // depth - pre-checked as non-negative
2300 // value_ptr - pre-checked for NULL
2301 jvmtiError
2302 JvmtiEnv::GetLocalLong(jthread thread, jint depth, jint slot, jlong* value_ptr) {
2303   jvmtiError err = JVMTI_ERROR_NONE;
2304   JavaThread* java_thread = NULL;
2305   JavaThread* current_thread = JavaThread::current();
2306   // rm object is created to clean up the javaVFrame created in
2307   // doit_prologue(), but after doit() is finished with it.
2308   ResourceMark rm(current_thread);
2309   HandleMark hm(current_thread);
2310   oop thread_obj = JNIHandles::resolve_external_guard(thread);
2311 
2312   if (java_lang_VirtualThread::is_instance(thread_obj)) {
2313     // Support for virtual threads
2314     VM_VirtualThreadGetOrSetLocal op(this, Handle(current_thread, thread_obj),
2315                                    depth, slot, T_LONG);
2316     VMThread::execute(&op);
2317     err = op.result();
2318     if (err == JVMTI_ERROR_NONE) {
2319       *value_ptr = op.value().j;
2320     }
2321   } else {
2322     // Support for ordinary threads
2323     ThreadsListHandle tlh(current_thread);
2324     err = get_JavaThread(tlh.list(), thread, &java_thread);
2325     if (err != JVMTI_ERROR_NONE) {
2326       return err;
2327     }
2328     VM_GetOrSetLocal op(java_thread, depth, slot, T_LONG);
2329     VMThread::execute(&op);
2330     err = op.result();
2331     if (err == JVMTI_ERROR_NONE) {
2332       *value_ptr = op.value().j;
2333     }
2334   }
2335   return err;
2336 } /* end GetLocalLong */
2337 
2338 
2339 // Threads_lock NOT held
2340 // depth - pre-checked as non-negative
2341 // value_ptr - pre-checked for NULL
2342 jvmtiError
2343 JvmtiEnv::GetLocalFloat(jthread thread, jint depth, jint slot, jfloat* value_ptr) {
2344   jvmtiError err = JVMTI_ERROR_NONE;
2345   JavaThread* java_thread = NULL;
2346   JavaThread* current_thread = JavaThread::current();
2347   // rm object is created to clean up the javaVFrame created in
2348   // doit_prologue(), but after doit() is finished with it.
2349   ResourceMark rm(current_thread);
2350   HandleMark hm(current_thread);
2351   oop thread_obj = JNIHandles::resolve_external_guard(thread);
2352 
2353   if (java_lang_VirtualThread::is_instance(thread_obj)) {
2354     // Support for virtual threads
2355     VM_VirtualThreadGetOrSetLocal op(this, Handle(current_thread, thread_obj),
2356                                    depth, slot, T_FLOAT);
2357     VMThread::execute(&op);
2358     err = op.result();
2359     if (err == JVMTI_ERROR_NONE) {
2360       *value_ptr = op.value().f;
2361     }
2362   } else {
2363     // Support for ordinary threads
2364     ThreadsListHandle tlh(current_thread);
2365     err = get_JavaThread(tlh.list(), thread, &java_thread);
2366     if (err != JVMTI_ERROR_NONE) {
2367       return err;
2368     }
2369     VM_GetOrSetLocal op(java_thread, depth, slot, T_FLOAT);
2370     VMThread::execute(&op);
2371     err = op.result();
2372     if (err == JVMTI_ERROR_NONE) {
2373       *value_ptr = op.value().f;
2374     }
2375   }
2376   return err;
2377 } /* end GetLocalFloat */
2378 
2379 
2380 // Threads_lock NOT held
2381 // depth - pre-checked as non-negative
2382 // value_ptr - pre-checked for NULL
2383 jvmtiError
2384 JvmtiEnv::GetLocalDouble(jthread thread, jint depth, jint slot, jdouble* value_ptr) {
2385   jvmtiError err = JVMTI_ERROR_NONE;
2386   JavaThread* java_thread = NULL;
2387   JavaThread* current_thread = JavaThread::current();
2388   // rm object is created to clean up the javaVFrame created in
2389   // doit_prologue(), but after doit() is finished with it.
2390   ResourceMark rm(current_thread);
2391   HandleMark hm(current_thread);
2392   oop thread_obj = JNIHandles::resolve_external_guard(thread);
2393 
2394   if (java_lang_VirtualThread::is_instance(thread_obj)) {
2395     // Support for virtual threads
2396     VM_VirtualThreadGetOrSetLocal op(this, Handle(current_thread, thread_obj),
2397                                    depth, slot, T_DOUBLE);
2398     VMThread::execute(&op);
2399     err = op.result();
2400     if (err == JVMTI_ERROR_NONE) {
2401       *value_ptr = op.value().d;
2402     }
2403   } else {
2404     // Support for ordinary threads
2405     ThreadsListHandle tlh(current_thread);
2406     err = get_JavaThread(tlh.list(), thread, &java_thread);
2407     if (err != JVMTI_ERROR_NONE) {
2408       return err;
2409     }
2410     VM_GetOrSetLocal op(java_thread, depth, slot, T_DOUBLE);
2411     VMThread::execute(&op);
2412     err = op.result();
2413     if (err == JVMTI_ERROR_NONE) {
2414       *value_ptr = op.value().d;
2415     }
2416   }
2417   return err;
2418 } /* end GetLocalDouble */
2419 
2420 
2421 // java_thread - protected by ThreadsListHandle and pre-checked
2422 // depth - pre-checked as non-negative
2423 jvmtiError
2424 JvmtiEnv::SetLocalObject(JavaThread* java_thread, jint depth, jint slot, jobject value) {
2425   // rm object is created to clean up the javaVFrame created in
2426   // doit_prologue(), but after doit() is finished with it.
2427   ResourceMark rm;
2428   jvalue val;
2429   val.l = value;
2430   VM_GetOrSetLocal op(java_thread, depth, slot, T_OBJECT, val);
2431   VMThread::execute(&op);
2432   return op.result();
2433 } /* end SetLocalObject */
2434 
2435 
2436 // java_thread - protected by ThreadsListHandle and pre-checked
2437 // depth - pre-checked as non-negative
2438 jvmtiError
2439 JvmtiEnv::SetLocalInt(JavaThread* java_thread, jint depth, jint slot, jint value) {
2440   // rm object is created to clean up the javaVFrame created in
2441   // doit_prologue(), but after doit() is finished with it.
2442   ResourceMark rm;
2443   jvalue val;
2444   val.i = value;
2445   VM_GetOrSetLocal op(java_thread, depth, slot, T_INT, val);
2446   VMThread::execute(&op);
2447   return op.result();
2448 } /* end SetLocalInt */
2449 
2450 
2451 // java_thread - protected by ThreadsListHandle and pre-checked
2452 // depth - pre-checked as non-negative
2453 jvmtiError
2454 JvmtiEnv::SetLocalLong(JavaThread* java_thread, jint depth, jint slot, jlong value) {
2455   // rm object is created to clean up the javaVFrame created in
2456   // doit_prologue(), but after doit() is finished with it.
2457   ResourceMark rm;
2458   jvalue val;
2459   val.j = value;
2460   VM_GetOrSetLocal op(java_thread, depth, slot, T_LONG, val);
2461   VMThread::execute(&op);
2462   return op.result();
2463 } /* end SetLocalLong */
2464 
2465 
2466 // java_thread - protected by ThreadsListHandle and pre-checked
2467 // depth - pre-checked as non-negative
2468 jvmtiError
2469 JvmtiEnv::SetLocalFloat(JavaThread* java_thread, jint depth, jint slot, jfloat value) {
2470   // rm object is created to clean up the javaVFrame created in
2471   // doit_prologue(), but after doit() is finished with it.
2472   ResourceMark rm;
2473   jvalue val;
2474   val.f = value;
2475   VM_GetOrSetLocal op(java_thread, depth, slot, T_FLOAT, val);
2476   VMThread::execute(&op);
2477   return op.result();
2478 } /* end SetLocalFloat */
2479 
2480 
2481 // java_thread - protected by ThreadsListHandle and pre-checked
2482 // depth - pre-checked as non-negative
2483 jvmtiError
2484 JvmtiEnv::SetLocalDouble(JavaThread* java_thread, jint depth, jint slot, jdouble value) {
2485   // rm object is created to clean up the javaVFrame created in
2486   // doit_prologue(), but after doit() is finished with it.
2487   ResourceMark rm;
2488   jvalue val;
2489   val.d = value;
2490   VM_GetOrSetLocal op(java_thread, depth, slot, T_DOUBLE, val);
2491   VMThread::execute(&op);
2492   return op.result();
2493 } /* end SetLocalDouble */
2494 
2495 
2496   //
2497   // Breakpoint functions
2498   //
2499 
2500 // method - pre-checked for validity, but may be NULL meaning obsolete method
2501 jvmtiError
2502 JvmtiEnv::SetBreakpoint(Method* method, jlocation location) {
2503   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
2504   if (location < 0) {   // simple invalid location check first
2505     return JVMTI_ERROR_INVALID_LOCATION;
2506   }
2507   // verify that the breakpoint is not past the end of the method
2508   if (location >= (jlocation) method->code_size()) {
2509     return JVMTI_ERROR_INVALID_LOCATION;
2510   }
2511 
2512   ResourceMark rm;
2513   JvmtiBreakpoint bp(method, location);
2514   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
2515   if (jvmti_breakpoints.set(bp) == JVMTI_ERROR_DUPLICATE)
2516     return JVMTI_ERROR_DUPLICATE;
2517 
2518   if (TraceJVMTICalls) {
2519     jvmti_breakpoints.print();
2520   }
2521 
2522   return JVMTI_ERROR_NONE;
2523 } /* end SetBreakpoint */
2524 
2525 
2526 // method - pre-checked for validity, but may be NULL meaning obsolete method
2527 jvmtiError
2528 JvmtiEnv::ClearBreakpoint(Method* method, jlocation location) {
2529   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
2530 
2531   if (location < 0) {   // simple invalid location check first
2532     return JVMTI_ERROR_INVALID_LOCATION;
2533   }
2534 
2535   // verify that the breakpoint is not past the end of the method
2536   if (location >= (jlocation) method->code_size()) {
2537     return JVMTI_ERROR_INVALID_LOCATION;
2538   }
2539 
2540   JvmtiBreakpoint bp(method, location);
2541 
2542   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
2543   if (jvmti_breakpoints.clear(bp) == JVMTI_ERROR_NOT_FOUND)
2544     return JVMTI_ERROR_NOT_FOUND;
2545 
2546   if (TraceJVMTICalls) {
2547     jvmti_breakpoints.print();
2548   }
2549 
2550   return JVMTI_ERROR_NONE;
2551 } /* end ClearBreakpoint */
2552 
2553 
2554   //
2555   // Watched Field functions
2556   //
2557 
2558 jvmtiError
2559 JvmtiEnv::SetFieldAccessWatch(fieldDescriptor* fdesc_ptr) {
2560   // make sure we haven't set this watch before
2561   if (fdesc_ptr->is_field_access_watched()) return JVMTI_ERROR_DUPLICATE;
2562   fdesc_ptr->set_is_field_access_watched(true);
2563 
2564   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_ACCESS, true);
2565 
2566   return JVMTI_ERROR_NONE;
2567 } /* end SetFieldAccessWatch */
2568 
2569 
2570 jvmtiError
2571 JvmtiEnv::ClearFieldAccessWatch(fieldDescriptor* fdesc_ptr) {
2572   // make sure we have a watch to clear
2573   if (!fdesc_ptr->is_field_access_watched()) return JVMTI_ERROR_NOT_FOUND;
2574   fdesc_ptr->set_is_field_access_watched(false);
2575 
2576   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_ACCESS, false);
2577 
2578   return JVMTI_ERROR_NONE;
2579 } /* end ClearFieldAccessWatch */
2580 
2581 
2582 jvmtiError
2583 JvmtiEnv::SetFieldModificationWatch(fieldDescriptor* fdesc_ptr) {
2584   // make sure we haven't set this watch before
2585   if (fdesc_ptr->is_field_modification_watched()) return JVMTI_ERROR_DUPLICATE;
2586   fdesc_ptr->set_is_field_modification_watched(true);
2587 
2588   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_MODIFICATION, true);
2589 
2590   return JVMTI_ERROR_NONE;
2591 } /* end SetFieldModificationWatch */
2592 
2593 
2594 jvmtiError
2595 JvmtiEnv::ClearFieldModificationWatch(fieldDescriptor* fdesc_ptr) {
2596    // make sure we have a watch to clear
2597   if (!fdesc_ptr->is_field_modification_watched()) return JVMTI_ERROR_NOT_FOUND;
2598   fdesc_ptr->set_is_field_modification_watched(false);
2599 
2600   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_MODIFICATION, false);
2601 
2602   return JVMTI_ERROR_NONE;
2603 } /* end ClearFieldModificationWatch */
2604 
2605   //
2606   // Class functions
2607   //
2608 
2609 
2610 // k_mirror - may be primitive, this must be checked
2611 // signature_ptr - NULL is a valid value, must be checked
2612 // generic_ptr - NULL is a valid value, must be checked
2613 jvmtiError
2614 JvmtiEnv::GetClassSignature(oop k_mirror, char** signature_ptr, char** generic_ptr) {
2615   ResourceMark rm;
2616   bool isPrimitive = java_lang_Class::is_primitive(k_mirror);
2617   Klass* k = NULL;
2618   if (!isPrimitive) {
2619     k = java_lang_Class::as_Klass(k_mirror);
2620     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2621   }
2622   if (signature_ptr != NULL) {
2623     char* result = NULL;
2624     if (isPrimitive) {
2625       char tchar = type2char(java_lang_Class::primitive_type(k_mirror));
2626       result = (char*) jvmtiMalloc(2);
2627       result[0] = tchar;
2628       result[1] = '\0';
2629     } else {
2630       const char* class_sig = k->signature_name();
2631       result = (char *) jvmtiMalloc(strlen(class_sig)+1);
2632       strcpy(result, class_sig);
2633     }
2634     *signature_ptr = result;
2635   }
2636   if (generic_ptr != NULL) {
2637     *generic_ptr = NULL;
2638     if (!isPrimitive && k->is_instance_klass()) {
2639       Symbol* soo = InstanceKlass::cast(k)->generic_signature();
2640       if (soo != NULL) {
2641         const char *gen_sig = soo->as_C_string();
2642         if (gen_sig != NULL) {
2643           char* gen_result;
2644           jvmtiError err = allocate(strlen(gen_sig) + 1,
2645                                     (unsigned char **)&gen_result);
2646           if (err != JVMTI_ERROR_NONE) {
2647             return err;
2648           }
2649           strcpy(gen_result, gen_sig);
2650           *generic_ptr = gen_result;
2651         }
2652       }
2653     }
2654   }
2655   return JVMTI_ERROR_NONE;
2656 } /* end GetClassSignature */
2657 
2658 
2659 // k_mirror - may be primitive, this must be checked
2660 // status_ptr - pre-checked for NULL
2661 jvmtiError
2662 JvmtiEnv::GetClassStatus(oop k_mirror, jint* status_ptr) {
2663   jint result = 0;
2664   if (java_lang_Class::is_primitive(k_mirror)) {
2665     result |= JVMTI_CLASS_STATUS_PRIMITIVE;
2666   } else {
2667     Klass* k = java_lang_Class::as_Klass(k_mirror);
2668     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2669     result = k->jvmti_class_status();
2670   }
2671   *status_ptr = result;
2672 
2673   return JVMTI_ERROR_NONE;
2674 } /* end GetClassStatus */
2675 
2676 
2677 // k_mirror - may be primitive, this must be checked
2678 // source_name_ptr - pre-checked for NULL
2679 jvmtiError
2680 JvmtiEnv::GetSourceFileName(oop k_mirror, char** source_name_ptr) {
2681   if (java_lang_Class::is_primitive(k_mirror)) {
2682      return JVMTI_ERROR_ABSENT_INFORMATION;
2683   }
2684   Klass* k_klass = java_lang_Class::as_Klass(k_mirror);
2685   NULL_CHECK(k_klass, JVMTI_ERROR_INVALID_CLASS);
2686 
2687   if (!k_klass->is_instance_klass()) {
2688     return JVMTI_ERROR_ABSENT_INFORMATION;
2689   }
2690 
2691   Symbol* sfnOop = InstanceKlass::cast(k_klass)->source_file_name();
2692   NULL_CHECK(sfnOop, JVMTI_ERROR_ABSENT_INFORMATION);
2693   {
2694     JavaThread* current_thread  = JavaThread::current();
2695     ResourceMark rm(current_thread);
2696     const char* sfncp = (const char*) sfnOop->as_C_string();
2697     *source_name_ptr = (char *) jvmtiMalloc(strlen(sfncp)+1);
2698     strcpy(*source_name_ptr, sfncp);
2699   }
2700 
2701   return JVMTI_ERROR_NONE;
2702 } /* end GetSourceFileName */
2703 
2704 
2705 // k_mirror - may be primitive, this must be checked
2706 // modifiers_ptr - pre-checked for NULL
2707 jvmtiError
2708 JvmtiEnv::GetClassModifiers(oop k_mirror, jint* modifiers_ptr) {
2709   JavaThread* current_thread  = JavaThread::current();
2710   jint result = 0;
2711   if (!java_lang_Class::is_primitive(k_mirror)) {
2712     Klass* k = java_lang_Class::as_Klass(k_mirror);
2713     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2714     result = k->compute_modifier_flags();
2715 
2716     // Reset the deleted  ACC_SUPER bit (deleted in compute_modifier_flags()).
2717     if (k->is_super()) {
2718       result |= JVM_ACC_SUPER;
2719     }
2720   } else {
2721     result = (JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
2722   }
2723   *modifiers_ptr = result;
2724 
2725   return JVMTI_ERROR_NONE;
2726 } /* end GetClassModifiers */
2727 
2728 
2729 // k_mirror - may be primitive, this must be checked
2730 // method_count_ptr - pre-checked for NULL
2731 // methods_ptr - pre-checked for NULL
2732 jvmtiError
2733 JvmtiEnv::GetClassMethods(oop k_mirror, jint* method_count_ptr, jmethodID** methods_ptr) {
2734   JavaThread* current_thread  = JavaThread::current();
2735   HandleMark hm(current_thread);
2736 
2737   if (java_lang_Class::is_primitive(k_mirror)) {
2738     *method_count_ptr = 0;
2739     *methods_ptr = (jmethodID*) jvmtiMalloc(0 * sizeof(jmethodID));
2740     return JVMTI_ERROR_NONE;
2741   }
2742   Klass* k = java_lang_Class::as_Klass(k_mirror);
2743   NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2744 
2745   // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2746   if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) )) {
2747     return JVMTI_ERROR_CLASS_NOT_PREPARED;
2748   }
2749 
2750   if (!k->is_instance_klass()) {
2751     *method_count_ptr = 0;
2752     *methods_ptr = (jmethodID*) jvmtiMalloc(0 * sizeof(jmethodID));
2753     return JVMTI_ERROR_NONE;
2754   }
2755   InstanceKlass* ik = InstanceKlass::cast(k);
2756   // Allocate the result and fill it in
2757   int result_length = ik->methods()->length();
2758   jmethodID* result_list = (jmethodID*)jvmtiMalloc(result_length * sizeof(jmethodID));
2759   int index;
2760   bool jmethodids_found = true;
2761   int skipped = 0;  // skip overpass methods
2762 
2763   for (index = 0; index < result_length; index++) {
2764     Method* m = ik->methods()->at(index);
2765     // Depending on can_maintain_original_method_order capability use the original
2766     // method ordering indices stored in the class, so we can emit jmethodIDs in
2767     // the order they appeared in the class file or just copy in current order.
2768     int result_index = JvmtiExport::can_maintain_original_method_order() ? ik->method_ordering()->at(index) : index;
2769     assert(result_index >= 0 && result_index < result_length, "invalid original method index");
2770     if (m->is_overpass()) {
2771       result_list[result_index] = NULL;
2772       skipped++;
2773       continue;
2774     }
2775     jmethodID id;
2776     if (jmethodids_found) {
2777       id = m->find_jmethod_id_or_null();
2778       if (id == NULL) {
2779         // If we find an uninitialized value, make sure there is
2780         // enough space for all the uninitialized values we might
2781         // find.
2782         ik->ensure_space_for_methodids(index);
2783         jmethodids_found = false;
2784         id = m->jmethod_id();
2785       }
2786     } else {
2787       id = m->jmethod_id();
2788     }
2789     result_list[result_index] = id;
2790   }
2791 
2792   // Fill in return value.
2793   if (skipped > 0) {
2794     // copy results skipping NULL methodIDs
2795     *methods_ptr = (jmethodID*)jvmtiMalloc((result_length - skipped) * sizeof(jmethodID));
2796     *method_count_ptr = result_length - skipped;
2797     for (index = 0, skipped = 0; index < result_length; index++) {
2798       if (result_list[index] == NULL) {
2799         skipped++;
2800       } else {
2801         (*methods_ptr)[index - skipped] = result_list[index];
2802       }
2803     }
2804     deallocate((unsigned char *)result_list);
2805   } else {
2806     *method_count_ptr = result_length;
2807     *methods_ptr = result_list;
2808   }
2809 
2810   return JVMTI_ERROR_NONE;
2811 } /* end GetClassMethods */
2812 
2813 
2814 // k_mirror - may be primitive, this must be checked
2815 // field_count_ptr - pre-checked for NULL
2816 // fields_ptr - pre-checked for NULL
2817 jvmtiError
2818 JvmtiEnv::GetClassFields(oop k_mirror, jint* field_count_ptr, jfieldID** fields_ptr) {
2819   if (java_lang_Class::is_primitive(k_mirror)) {
2820     *field_count_ptr = 0;
2821     *fields_ptr = (jfieldID*) jvmtiMalloc(0 * sizeof(jfieldID));
2822     return JVMTI_ERROR_NONE;
2823   }
2824   JavaThread* current_thread = JavaThread::current();
2825   HandleMark hm(current_thread);
2826   Klass* k = java_lang_Class::as_Klass(k_mirror);
2827   NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2828 
2829   // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2830   if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) )) {
2831     return JVMTI_ERROR_CLASS_NOT_PREPARED;
2832   }
2833 
2834   if (!k->is_instance_klass()) {
2835     *field_count_ptr = 0;
2836     *fields_ptr = (jfieldID*) jvmtiMalloc(0 * sizeof(jfieldID));
2837     return JVMTI_ERROR_NONE;
2838   }
2839 
2840 
2841   InstanceKlass* ik = InstanceKlass::cast(k);
2842 
2843   int result_count = 0;
2844   // First, count the fields.
2845   FilteredFieldStream flds(ik, true, true);
2846   result_count = flds.field_count();
2847 
2848   // Allocate the result and fill it in
2849   jfieldID* result_list = (jfieldID*) jvmtiMalloc(result_count * sizeof(jfieldID));
2850   // The JVMTI spec requires fields in the order they occur in the class file,
2851   // this is the reverse order of what FieldStream hands out.
2852   int id_index = (result_count - 1);
2853 
2854   for (FilteredFieldStream src_st(ik, true, true); !src_st.eos(); src_st.next()) {
2855     result_list[id_index--] = jfieldIDWorkaround::to_jfieldID(
2856                                             ik, src_st.offset(),
2857                                             src_st.access_flags().is_static());
2858   }
2859   assert(id_index == -1, "just checking");
2860   // Fill in the results
2861   *field_count_ptr = result_count;
2862   *fields_ptr = result_list;
2863 
2864   return JVMTI_ERROR_NONE;
2865 } /* end GetClassFields */
2866 
2867 
2868 // k_mirror - may be primitive, this must be checked
2869 // interface_count_ptr - pre-checked for NULL
2870 // interfaces_ptr - pre-checked for NULL
2871 jvmtiError
2872 JvmtiEnv::GetImplementedInterfaces(oop k_mirror, jint* interface_count_ptr, jclass** interfaces_ptr) {
2873   {
2874     if (java_lang_Class::is_primitive(k_mirror)) {
2875       *interface_count_ptr = 0;
2876       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2877       return JVMTI_ERROR_NONE;
2878     }
2879     JavaThread* current_thread = JavaThread::current();
2880     HandleMark hm(current_thread);
2881     Klass* k = java_lang_Class::as_Klass(k_mirror);
2882     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2883 
2884     // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2885     if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) ))
2886       return JVMTI_ERROR_CLASS_NOT_PREPARED;
2887 
2888     if (!k->is_instance_klass()) {
2889       *interface_count_ptr = 0;
2890       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2891       return JVMTI_ERROR_NONE;
2892     }
2893 
2894     Array<InstanceKlass*>* interface_list = InstanceKlass::cast(k)->local_interfaces();
2895     const int result_length = (interface_list == NULL ? 0 : interface_list->length());
2896     jclass* result_list = (jclass*) jvmtiMalloc(result_length * sizeof(jclass));
2897     for (int i_index = 0; i_index < result_length; i_index += 1) {
2898       InstanceKlass* klass_at = interface_list->at(i_index);
2899       assert(klass_at->is_klass(), "interfaces must be Klass*s");
2900       assert(klass_at->is_interface(), "interfaces must be interfaces");
2901       oop mirror_at = klass_at->java_mirror();
2902       Handle handle_at = Handle(current_thread, mirror_at);
2903       result_list[i_index] = (jclass) jni_reference(handle_at);
2904     }
2905     *interface_count_ptr = result_length;
2906     *interfaces_ptr = result_list;
2907   }
2908 
2909   return JVMTI_ERROR_NONE;
2910 } /* end GetImplementedInterfaces */
2911 
2912 
2913 // k_mirror - may be primitive, this must be checked
2914 // minor_version_ptr - pre-checked for NULL
2915 // major_version_ptr - pre-checked for NULL
2916 jvmtiError
2917 JvmtiEnv::GetClassVersionNumbers(oop k_mirror, jint* minor_version_ptr, jint* major_version_ptr) {
2918   if (java_lang_Class::is_primitive(k_mirror)) {
2919     return JVMTI_ERROR_ABSENT_INFORMATION;
2920   }
2921   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2922 
2923   jint status = klass->jvmti_class_status();
2924   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2925     return JVMTI_ERROR_INVALID_CLASS;
2926   }
2927   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2928     return JVMTI_ERROR_ABSENT_INFORMATION;
2929   }
2930 
2931   InstanceKlass* ik = InstanceKlass::cast(klass);
2932   *minor_version_ptr = ik->minor_version();
2933   *major_version_ptr = ik->major_version();
2934 
2935   return JVMTI_ERROR_NONE;
2936 } /* end GetClassVersionNumbers */
2937 
2938 
2939 // k_mirror - may be primitive, this must be checked
2940 // constant_pool_count_ptr - pre-checked for NULL
2941 // constant_pool_byte_count_ptr - pre-checked for NULL
2942 // constant_pool_bytes_ptr - pre-checked for NULL
2943 jvmtiError
2944 JvmtiEnv::GetConstantPool(oop k_mirror, jint* constant_pool_count_ptr, jint* constant_pool_byte_count_ptr, unsigned char** constant_pool_bytes_ptr) {
2945   if (java_lang_Class::is_primitive(k_mirror)) {
2946     return JVMTI_ERROR_ABSENT_INFORMATION;
2947   }
2948 
2949   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2950   Thread *thread = Thread::current();
2951   ResourceMark rm(thread);
2952 
2953   jint status = klass->jvmti_class_status();
2954   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2955     return JVMTI_ERROR_INVALID_CLASS;
2956   }
2957   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2958     return JVMTI_ERROR_ABSENT_INFORMATION;
2959   }
2960 
2961   InstanceKlass* ik = InstanceKlass::cast(klass);
2962   JvmtiConstantPoolReconstituter reconstituter(ik);
2963   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2964     return reconstituter.get_error();
2965   }
2966 
2967   unsigned char *cpool_bytes;
2968   int cpool_size = reconstituter.cpool_size();
2969   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2970     return reconstituter.get_error();
2971   }
2972   jvmtiError res = allocate(cpool_size, &cpool_bytes);
2973   if (res != JVMTI_ERROR_NONE) {
2974     return res;
2975   }
2976   reconstituter.copy_cpool_bytes(cpool_bytes);
2977   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2978     return reconstituter.get_error();
2979   }
2980 
2981   constantPoolHandle  constants(thread, ik->constants());
2982   *constant_pool_count_ptr      = constants->length();
2983   *constant_pool_byte_count_ptr = cpool_size;
2984   *constant_pool_bytes_ptr      = cpool_bytes;
2985 
2986   return JVMTI_ERROR_NONE;
2987 } /* end GetConstantPool */
2988 
2989 
2990 // k_mirror - may be primitive, this must be checked
2991 // is_interface_ptr - pre-checked for NULL
2992 jvmtiError
2993 JvmtiEnv::IsInterface(oop k_mirror, jboolean* is_interface_ptr) {
2994   {
2995     bool result = false;
2996     if (!java_lang_Class::is_primitive(k_mirror)) {
2997       Klass* k = java_lang_Class::as_Klass(k_mirror);
2998       if (k != NULL && k->is_interface()) {
2999         result = true;
3000       }
3001     }
3002     *is_interface_ptr = result;
3003   }
3004 
3005   return JVMTI_ERROR_NONE;
3006 } /* end IsInterface */
3007 
3008 
3009 // k_mirror - may be primitive, this must be checked
3010 // is_array_class_ptr - pre-checked for NULL
3011 jvmtiError
3012 JvmtiEnv::IsArrayClass(oop k_mirror, jboolean* is_array_class_ptr) {
3013   {
3014     bool result = false;
3015     if (!java_lang_Class::is_primitive(k_mirror)) {
3016       Klass* k = java_lang_Class::as_Klass(k_mirror);
3017       if (k != NULL && k->is_array_klass()) {
3018         result = true;
3019       }
3020     }
3021     *is_array_class_ptr = result;
3022   }
3023 
3024   return JVMTI_ERROR_NONE;
3025 } /* end IsArrayClass */
3026 
3027 
3028 // k_mirror - may be primitive, this must be checked
3029 // classloader_ptr - pre-checked for NULL
3030 jvmtiError
3031 JvmtiEnv::GetClassLoader(oop k_mirror, jobject* classloader_ptr) {
3032   {
3033     if (java_lang_Class::is_primitive(k_mirror)) {
3034       *classloader_ptr = (jclass) jni_reference(Handle());
3035       return JVMTI_ERROR_NONE;
3036     }
3037     JavaThread* current_thread = JavaThread::current();
3038     HandleMark hm(current_thread);
3039     Klass* k = java_lang_Class::as_Klass(k_mirror);
3040     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
3041 
3042     oop result_oop = k->class_loader();
3043     if (result_oop == NULL) {
3044       *classloader_ptr = (jclass) jni_reference(Handle());
3045       return JVMTI_ERROR_NONE;
3046     }
3047     Handle result_handle = Handle(current_thread, result_oop);
3048     jclass result_jnihandle = (jclass) jni_reference(result_handle);
3049     *classloader_ptr = result_jnihandle;
3050   }
3051   return JVMTI_ERROR_NONE;
3052 } /* end GetClassLoader */
3053 
3054 
3055 // k_mirror - may be primitive, this must be checked
3056 // source_debug_extension_ptr - pre-checked for NULL
3057 jvmtiError
3058 JvmtiEnv::GetSourceDebugExtension(oop k_mirror, char** source_debug_extension_ptr) {
3059   {
3060     if (java_lang_Class::is_primitive(k_mirror)) {
3061       return JVMTI_ERROR_ABSENT_INFORMATION;
3062     }
3063     Klass* k = java_lang_Class::as_Klass(k_mirror);
3064     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
3065     if (!k->is_instance_klass()) {
3066       return JVMTI_ERROR_ABSENT_INFORMATION;
3067     }
3068     const char* sde = InstanceKlass::cast(k)->source_debug_extension();
3069     NULL_CHECK(sde, JVMTI_ERROR_ABSENT_INFORMATION);
3070 
3071     {
3072       *source_debug_extension_ptr = (char *) jvmtiMalloc(strlen(sde)+1);
3073       strcpy(*source_debug_extension_ptr, sde);
3074     }
3075   }
3076 
3077   return JVMTI_ERROR_NONE;
3078 } /* end GetSourceDebugExtension */
3079 
3080   //
3081   // Object functions
3082   //
3083 
3084 // hash_code_ptr - pre-checked for NULL
3085 jvmtiError
3086 JvmtiEnv::GetObjectHashCode(jobject object, jint* hash_code_ptr) {
3087   oop mirror = JNIHandles::resolve_external_guard(object);
3088   NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
3089   NULL_CHECK(hash_code_ptr, JVMTI_ERROR_NULL_POINTER);
3090 
3091   {
3092     jint result = (jint) mirror->identity_hash();
3093     *hash_code_ptr = result;
3094   }
3095   return JVMTI_ERROR_NONE;
3096 } /* end GetObjectHashCode */
3097 
3098 
3099 // info_ptr - pre-checked for NULL
3100 jvmtiError
3101 JvmtiEnv::GetObjectMonitorUsage(jobject object, jvmtiMonitorUsage* info_ptr) {
3102   // This needs to be performed at a safepoint to gather stable data
3103   // because monitor owner / waiters might not be suspended.
3104   VM_GetObjectMonitorUsage op(this, JavaThread::current(), object, info_ptr);
3105   VMThread::execute(&op);
3106   return op.result();
3107 } /* end GetObjectMonitorUsage */
3108 
3109 
3110   //
3111   // Field functions
3112   //
3113 
3114 // name_ptr - NULL is a valid value, must be checked
3115 // signature_ptr - NULL is a valid value, must be checked
3116 // generic_ptr - NULL is a valid value, must be checked
3117 jvmtiError
3118 JvmtiEnv::GetFieldName(fieldDescriptor* fdesc_ptr, char** name_ptr, char** signature_ptr, char** generic_ptr) {
3119   JavaThread* current_thread  = JavaThread::current();
3120   ResourceMark rm(current_thread);
3121   if (name_ptr == NULL) {
3122     // just don't return the name
3123   } else {
3124     const char* fieldName = fdesc_ptr->name()->as_C_string();
3125     *name_ptr =  (char*) jvmtiMalloc(strlen(fieldName) + 1);
3126     if (*name_ptr == NULL)
3127       return JVMTI_ERROR_OUT_OF_MEMORY;
3128     strcpy(*name_ptr, fieldName);
3129   }
3130   if (signature_ptr== NULL) {
3131     // just don't return the signature
3132   } else {
3133     const char* fieldSignature = fdesc_ptr->signature()->as_C_string();
3134     *signature_ptr = (char*) jvmtiMalloc(strlen(fieldSignature) + 1);
3135     if (*signature_ptr == NULL)
3136       return JVMTI_ERROR_OUT_OF_MEMORY;
3137     strcpy(*signature_ptr, fieldSignature);
3138   }
3139   if (generic_ptr != NULL) {
3140     *generic_ptr = NULL;
3141     Symbol* soop = fdesc_ptr->generic_signature();
3142     if (soop != NULL) {
3143       const char* gen_sig = soop->as_C_string();
3144       if (gen_sig != NULL) {
3145         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
3146         if (err != JVMTI_ERROR_NONE) {
3147           return err;
3148         }
3149         strcpy(*generic_ptr, gen_sig);
3150       }
3151     }
3152   }
3153   return JVMTI_ERROR_NONE;
3154 } /* end GetFieldName */
3155 
3156 
3157 // declaring_class_ptr - pre-checked for NULL
3158 jvmtiError
3159 JvmtiEnv::GetFieldDeclaringClass(fieldDescriptor* fdesc_ptr, jclass* declaring_class_ptr) {
3160 
3161   *declaring_class_ptr = get_jni_class_non_null(fdesc_ptr->field_holder());
3162   return JVMTI_ERROR_NONE;
3163 } /* end GetFieldDeclaringClass */
3164 
3165 
3166 // modifiers_ptr - pre-checked for NULL
3167 jvmtiError
3168 JvmtiEnv::GetFieldModifiers(fieldDescriptor* fdesc_ptr, jint* modifiers_ptr) {
3169 
3170   AccessFlags resultFlags = fdesc_ptr->access_flags();
3171   jint result = resultFlags.as_int();
3172   *modifiers_ptr = result;
3173 
3174   return JVMTI_ERROR_NONE;
3175 } /* end GetFieldModifiers */
3176 
3177 
3178 // is_synthetic_ptr - pre-checked for NULL
3179 jvmtiError
3180 JvmtiEnv::IsFieldSynthetic(fieldDescriptor* fdesc_ptr, jboolean* is_synthetic_ptr) {
3181   *is_synthetic_ptr = fdesc_ptr->is_synthetic();
3182   return JVMTI_ERROR_NONE;
3183 } /* end IsFieldSynthetic */
3184 
3185 
3186   //
3187   // Method functions
3188   //
3189 
3190 // method - pre-checked for validity, but may be NULL meaning obsolete method
3191 // name_ptr - NULL is a valid value, must be checked
3192 // signature_ptr - NULL is a valid value, must be checked
3193 // generic_ptr - NULL is a valid value, must be checked
3194 jvmtiError
3195 JvmtiEnv::GetMethodName(Method* method, char** name_ptr, char** signature_ptr, char** generic_ptr) {
3196   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3197   JavaThread* current_thread  = JavaThread::current();
3198 
3199   ResourceMark rm(current_thread); // get the utf8 name and signature
3200   if (name_ptr == NULL) {
3201     // just don't return the name
3202   } else {
3203     const char* utf8_name = (const char *) method->name()->as_utf8();
3204     *name_ptr = (char *) jvmtiMalloc(strlen(utf8_name)+1);
3205     strcpy(*name_ptr, utf8_name);
3206   }
3207   if (signature_ptr == NULL) {
3208     // just don't return the signature
3209   } else {
3210     const char* utf8_signature = (const char *) method->signature()->as_utf8();
3211     *signature_ptr = (char *) jvmtiMalloc(strlen(utf8_signature) + 1);
3212     strcpy(*signature_ptr, utf8_signature);
3213   }
3214 
3215   if (generic_ptr != NULL) {
3216     *generic_ptr = NULL;
3217     Symbol* soop = method->generic_signature();
3218     if (soop != NULL) {
3219       const char* gen_sig = soop->as_C_string();
3220       if (gen_sig != NULL) {
3221         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
3222         if (err != JVMTI_ERROR_NONE) {
3223           return err;
3224         }
3225         strcpy(*generic_ptr, gen_sig);
3226       }
3227     }
3228   }
3229   return JVMTI_ERROR_NONE;
3230 } /* end GetMethodName */
3231 
3232 
3233 // method - pre-checked for validity, but may be NULL meaning obsolete method
3234 // declaring_class_ptr - pre-checked for NULL
3235 jvmtiError
3236 JvmtiEnv::GetMethodDeclaringClass(Method* method, jclass* declaring_class_ptr) {
3237   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3238   (*declaring_class_ptr) = get_jni_class_non_null(method->method_holder());
3239   return JVMTI_ERROR_NONE;
3240 } /* end GetMethodDeclaringClass */
3241 
3242 
3243 // method - pre-checked for validity, but may be NULL meaning obsolete method
3244 // modifiers_ptr - pre-checked for NULL
3245 jvmtiError
3246 JvmtiEnv::GetMethodModifiers(Method* method, jint* modifiers_ptr) {
3247   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3248   (*modifiers_ptr) = method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
3249   return JVMTI_ERROR_NONE;
3250 } /* end GetMethodModifiers */
3251 
3252 
3253 // method - pre-checked for validity, but may be NULL meaning obsolete method
3254 // max_ptr - pre-checked for NULL
3255 jvmtiError
3256 JvmtiEnv::GetMaxLocals(Method* method, jint* max_ptr) {
3257   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3258   // get max stack
3259   (*max_ptr) = method->max_locals();
3260   return JVMTI_ERROR_NONE;
3261 } /* end GetMaxLocals */
3262 
3263 
3264 // method - pre-checked for validity, but may be NULL meaning obsolete method
3265 // size_ptr - pre-checked for NULL
3266 jvmtiError
3267 JvmtiEnv::GetArgumentsSize(Method* method, jint* size_ptr) {
3268   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3269   // get size of arguments
3270 
3271   (*size_ptr) = method->size_of_parameters();
3272   return JVMTI_ERROR_NONE;
3273 } /* end GetArgumentsSize */
3274 
3275 
3276 // method - pre-checked for validity, but may be NULL meaning obsolete method
3277 // entry_count_ptr - pre-checked for NULL
3278 // table_ptr - pre-checked for NULL
3279 jvmtiError
3280 JvmtiEnv::GetLineNumberTable(Method* method, jint* entry_count_ptr, jvmtiLineNumberEntry** table_ptr) {
3281   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3282   if (!method->has_linenumber_table()) {
3283     return (JVMTI_ERROR_ABSENT_INFORMATION);
3284   }
3285 
3286   // The line number table is compressed so we don't know how big it is until decompressed.
3287   // Decompression is really fast so we just do it twice.
3288 
3289   // Compute size of table
3290   jint num_entries = 0;
3291   CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
3292   while (stream.read_pair()) {
3293     num_entries++;
3294   }
3295   jvmtiLineNumberEntry *jvmti_table =
3296             (jvmtiLineNumberEntry *)jvmtiMalloc(num_entries * (sizeof(jvmtiLineNumberEntry)));
3297 
3298   // Fill jvmti table
3299   if (num_entries > 0) {
3300     int index = 0;
3301     CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
3302     while (stream.read_pair()) {
3303       jvmti_table[index].start_location = (jlocation) stream.bci();
3304       jvmti_table[index].line_number = (jint) stream.line();
3305       index++;
3306     }
3307     assert(index == num_entries, "sanity check");
3308   }
3309 
3310   // Set up results
3311   (*entry_count_ptr) = num_entries;
3312   (*table_ptr) = jvmti_table;
3313 
3314   return JVMTI_ERROR_NONE;
3315 } /* end GetLineNumberTable */
3316 
3317 
3318 // method - pre-checked for validity, but may be NULL meaning obsolete method
3319 // start_location_ptr - pre-checked for NULL
3320 // end_location_ptr - pre-checked for NULL
3321 jvmtiError
3322 JvmtiEnv::GetMethodLocation(Method* method, jlocation* start_location_ptr, jlocation* end_location_ptr) {
3323 
3324   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3325   // get start and end location
3326   (*end_location_ptr) = (jlocation) (method->code_size() - 1);
3327   if (method->code_size() == 0) {
3328     // there is no code so there is no start location
3329     (*start_location_ptr) = (jlocation)(-1);
3330   } else {
3331     (*start_location_ptr) = (jlocation)(0);
3332   }
3333 
3334   return JVMTI_ERROR_NONE;
3335 } /* end GetMethodLocation */
3336 
3337 
3338 // method - pre-checked for validity, but may be NULL meaning obsolete method
3339 // entry_count_ptr - pre-checked for NULL
3340 // table_ptr - pre-checked for NULL
3341 jvmtiError
3342 JvmtiEnv::GetLocalVariableTable(Method* method, jint* entry_count_ptr, jvmtiLocalVariableEntry** table_ptr) {
3343 
3344   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3345   JavaThread* current_thread  = JavaThread::current();
3346 
3347   // does the klass have any local variable information?
3348   InstanceKlass* ik = method->method_holder();
3349   if (!ik->access_flags().has_localvariable_table()) {
3350     return (JVMTI_ERROR_ABSENT_INFORMATION);
3351   }
3352 
3353   ConstantPool* constants = method->constants();
3354   NULL_CHECK(constants, JVMTI_ERROR_ABSENT_INFORMATION);
3355 
3356   // in the vm localvariable table representation, 6 consecutive elements in the table
3357   // represent a 6-tuple of shorts
3358   // [start_pc, length, name_index, descriptor_index, signature_index, index]
3359   jint num_entries = method->localvariable_table_length();
3360   jvmtiLocalVariableEntry *jvmti_table = (jvmtiLocalVariableEntry *)
3361                 jvmtiMalloc(num_entries * (sizeof(jvmtiLocalVariableEntry)));
3362 
3363   if (num_entries > 0) {
3364     LocalVariableTableElement* table = method->localvariable_table_start();
3365     for (int i = 0; i < num_entries; i++) {
3366       // get the 5 tuple information from the vm table
3367       jlocation start_location = (jlocation) table[i].start_bci;
3368       jint length = (jint) table[i].length;
3369       int name_index = (int) table[i].name_cp_index;
3370       int signature_index = (int) table[i].descriptor_cp_index;
3371       int generic_signature_index = (int) table[i].signature_cp_index;
3372       jint slot = (jint) table[i].slot;
3373 
3374       // get utf8 name and signature
3375       char *name_buf = NULL;
3376       char *sig_buf = NULL;
3377       char *gen_sig_buf = NULL;
3378       {
3379         ResourceMark rm(current_thread);
3380 
3381         const char *utf8_name = (const char *) constants->symbol_at(name_index)->as_utf8();
3382         name_buf = (char *) jvmtiMalloc(strlen(utf8_name)+1);
3383         strcpy(name_buf, utf8_name);
3384 
3385         const char *utf8_signature = (const char *) constants->symbol_at(signature_index)->as_utf8();
3386         sig_buf = (char *) jvmtiMalloc(strlen(utf8_signature)+1);
3387         strcpy(sig_buf, utf8_signature);
3388 
3389         if (generic_signature_index > 0) {
3390           const char *utf8_gen_sign = (const char *)
3391                                        constants->symbol_at(generic_signature_index)->as_utf8();
3392           gen_sig_buf = (char *) jvmtiMalloc(strlen(utf8_gen_sign)+1);
3393           strcpy(gen_sig_buf, utf8_gen_sign);
3394         }
3395       }
3396 
3397       // fill in the jvmti local variable table
3398       jvmti_table[i].start_location = start_location;
3399       jvmti_table[i].length = length;
3400       jvmti_table[i].name = name_buf;
3401       jvmti_table[i].signature = sig_buf;
3402       jvmti_table[i].generic_signature = gen_sig_buf;
3403       jvmti_table[i].slot = slot;
3404     }
3405   }
3406 
3407   // set results
3408   (*entry_count_ptr) = num_entries;
3409   (*table_ptr) = jvmti_table;
3410 
3411   return JVMTI_ERROR_NONE;
3412 } /* end GetLocalVariableTable */
3413 
3414 
3415 // method - pre-checked for validity, but may be NULL meaning obsolete method
3416 // bytecode_count_ptr - pre-checked for NULL
3417 // bytecodes_ptr - pre-checked for NULL
3418 jvmtiError
3419 JvmtiEnv::GetBytecodes(Method* method, jint* bytecode_count_ptr, unsigned char** bytecodes_ptr) {
3420   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3421 
3422   methodHandle mh(Thread::current(), method);
3423   jint size = (jint)mh->code_size();
3424   jvmtiError err = allocate(size, bytecodes_ptr);
3425   if (err != JVMTI_ERROR_NONE) {
3426     return err;
3427   }
3428 
3429   (*bytecode_count_ptr) = size;
3430   // get byte codes
3431   JvmtiClassFileReconstituter::copy_bytecodes(mh, *bytecodes_ptr);
3432 
3433   return JVMTI_ERROR_NONE;
3434 } /* end GetBytecodes */
3435 
3436 
3437 // method - pre-checked for validity, but may be NULL meaning obsolete method
3438 // is_native_ptr - pre-checked for NULL
3439 jvmtiError
3440 JvmtiEnv::IsMethodNative(Method* method, jboolean* is_native_ptr) {
3441   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3442   (*is_native_ptr) = method->is_native();
3443   return JVMTI_ERROR_NONE;
3444 } /* end IsMethodNative */
3445 
3446 
3447 // method - pre-checked for validity, but may be NULL meaning obsolete method
3448 // is_synthetic_ptr - pre-checked for NULL
3449 jvmtiError
3450 JvmtiEnv::IsMethodSynthetic(Method* method, jboolean* is_synthetic_ptr) {
3451   NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID);
3452   (*is_synthetic_ptr) = method->is_synthetic();
3453   return JVMTI_ERROR_NONE;
3454 } /* end IsMethodSynthetic */
3455 
3456 
3457 // method - pre-checked for validity, but may be NULL meaning obsolete method
3458 // is_obsolete_ptr - pre-checked for NULL
3459 jvmtiError
3460 JvmtiEnv::IsMethodObsolete(Method* method, jboolean* is_obsolete_ptr) {
3461   if (use_version_1_0_semantics() &&
3462       get_capabilities()->can_redefine_classes == 0) {
3463     // This JvmtiEnv requested version 1.0 semantics and this function
3464     // requires the can_redefine_classes capability in version 1.0 so
3465     // we need to return an error here.
3466     return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3467   }
3468 
3469   if (method == NULL || method->is_obsolete()) {
3470     *is_obsolete_ptr = true;
3471   } else {
3472     *is_obsolete_ptr = false;
3473   }
3474   return JVMTI_ERROR_NONE;
3475 } /* end IsMethodObsolete */
3476 
3477   //
3478   // Raw Monitor functions
3479   //
3480 
3481 // name - pre-checked for NULL
3482 // monitor_ptr - pre-checked for NULL
3483 jvmtiError
3484 JvmtiEnv::CreateRawMonitor(const char* name, jrawMonitorID* monitor_ptr) {
3485   JvmtiRawMonitor* rmonitor = new JvmtiRawMonitor(name);
3486   NULL_CHECK(rmonitor, JVMTI_ERROR_OUT_OF_MEMORY);
3487 
3488   *monitor_ptr = (jrawMonitorID)rmonitor;
3489 
3490   return JVMTI_ERROR_NONE;
3491 } /* end CreateRawMonitor */
3492 
3493 
3494 // rmonitor - pre-checked for validity
3495 jvmtiError
3496 JvmtiEnv::DestroyRawMonitor(JvmtiRawMonitor * rmonitor) {
3497   if (Threads::number_of_threads() == 0) {
3498     // Remove this monitor from pending raw monitors list
3499     // if it has entered in onload or start phase.
3500     JvmtiPendingMonitors::destroy(rmonitor);
3501   } else {
3502     Thread* thread  = Thread::current();
3503     if (rmonitor->owner() == thread) {
3504       // The caller owns this monitor which we are about to destroy.
3505       // We exit the underlying synchronization object so that the
3506       // "delete monitor" call below can work without an assertion
3507       // failure on systems that don't like destroying synchronization
3508       // objects that are locked.
3509       int r;
3510       int recursion = rmonitor->recursions();
3511       for (int i = 0; i <= recursion; i++) {
3512         r = rmonitor->raw_exit(thread);
3513         assert(r == JvmtiRawMonitor::M_OK, "raw_exit should have worked");
3514         if (r != JvmtiRawMonitor::M_OK) {  // robustness
3515           return JVMTI_ERROR_INTERNAL;
3516         }
3517       }
3518     }
3519     if (rmonitor->owner() != NULL) {
3520       // The caller is trying to destroy a monitor that is locked by
3521       // someone else. While this is not forbidden by the JVMTI
3522       // spec, it will cause an assertion failure on systems that don't
3523       // like destroying synchronization objects that are locked.
3524       // We indicate a problem with the error return (and leak the
3525       // monitor's memory).
3526       return JVMTI_ERROR_NOT_MONITOR_OWNER;
3527     }
3528   }
3529 
3530   delete rmonitor;
3531 
3532   return JVMTI_ERROR_NONE;
3533 } /* end DestroyRawMonitor */
3534 
3535 
3536 // rmonitor - pre-checked for validity
3537 jvmtiError
3538 JvmtiEnv::RawMonitorEnter(JvmtiRawMonitor * rmonitor) {
3539   if (Threads::number_of_threads() == 0) {
3540     // No JavaThreads exist so JvmtiRawMonitor enter cannot be
3541     // used, add this raw monitor to the pending list.
3542     // The pending monitors will be actually entered when
3543     // the VM is setup.
3544     // See transition_pending_raw_monitors in create_vm()
3545     // in thread.cpp.
3546     JvmtiPendingMonitors::enter(rmonitor);
3547   } else {
3548     Thread* thread = Thread::current();
3549     // 8266889: raw_enter changes Java thread state, needs WXWrite
3550     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));
3551     rmonitor->raw_enter(thread);
3552   }
3553   return JVMTI_ERROR_NONE;
3554 } /* end RawMonitorEnter */
3555 
3556 
3557 // rmonitor - pre-checked for validity
3558 jvmtiError
3559 JvmtiEnv::RawMonitorExit(JvmtiRawMonitor * rmonitor) {
3560   jvmtiError err = JVMTI_ERROR_NONE;
3561 
3562   if (Threads::number_of_threads() == 0) {
3563     // No JavaThreads exist so just remove this monitor from the pending list.
3564     // Bool value from exit is false if rmonitor is not in the list.
3565     if (!JvmtiPendingMonitors::exit(rmonitor)) {
3566       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3567     }
3568   } else {
3569     Thread* thread = Thread::current();
3570     int r = rmonitor->raw_exit(thread);
3571     if (r == JvmtiRawMonitor::M_ILLEGAL_MONITOR_STATE) {
3572       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3573     }
3574   }
3575   return err;
3576 } /* end RawMonitorExit */
3577 
3578 
3579 // rmonitor - pre-checked for validity
3580 jvmtiError
3581 JvmtiEnv::RawMonitorWait(JvmtiRawMonitor * rmonitor, jlong millis) {
3582   Thread* thread = Thread::current();
3583   // 8266889: raw_wait changes Java thread state, needs WXWrite
3584   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));
3585   int r = rmonitor->raw_wait(millis, thread);
3586 
3587   switch (r) {
3588   case JvmtiRawMonitor::M_INTERRUPTED:
3589     return JVMTI_ERROR_INTERRUPT;
3590   case JvmtiRawMonitor::M_ILLEGAL_MONITOR_STATE:
3591     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3592   default:
3593     return JVMTI_ERROR_NONE;
3594   }
3595 } /* end RawMonitorWait */
3596 
3597 
3598 // rmonitor - pre-checked for validity
3599 jvmtiError
3600 JvmtiEnv::RawMonitorNotify(JvmtiRawMonitor * rmonitor) {
3601   Thread* thread = Thread::current();
3602   int r = rmonitor->raw_notify(thread);
3603 
3604   if (r == JvmtiRawMonitor::M_ILLEGAL_MONITOR_STATE) {
3605     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3606   }
3607   return JVMTI_ERROR_NONE;
3608 } /* end RawMonitorNotify */
3609 
3610 
3611 // rmonitor - pre-checked for validity
3612 jvmtiError
3613 JvmtiEnv::RawMonitorNotifyAll(JvmtiRawMonitor * rmonitor) {
3614   Thread* thread = Thread::current();
3615   int r = rmonitor->raw_notifyAll(thread);
3616 
3617   if (r == JvmtiRawMonitor::M_ILLEGAL_MONITOR_STATE) {
3618     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3619   }
3620   return JVMTI_ERROR_NONE;
3621 } /* end RawMonitorNotifyAll */
3622 
3623 
3624   //
3625   // JNI Function Interception functions
3626   //
3627 
3628 
3629 // function_table - pre-checked for NULL
3630 jvmtiError
3631 JvmtiEnv::SetJNIFunctionTable(const jniNativeInterface* function_table) {
3632   // Copy jni function table at safepoint.
3633   VM_JNIFunctionTableCopier copier(function_table);
3634   VMThread::execute(&copier);
3635 
3636   return JVMTI_ERROR_NONE;
3637 } /* end SetJNIFunctionTable */
3638 
3639 
3640 // function_table - pre-checked for NULL
3641 jvmtiError
3642 JvmtiEnv::GetJNIFunctionTable(jniNativeInterface** function_table) {
3643   *function_table=(jniNativeInterface*)jvmtiMalloc(sizeof(jniNativeInterface));
3644   if (*function_table == NULL)
3645     return JVMTI_ERROR_OUT_OF_MEMORY;
3646   memcpy(*function_table,(JavaThread::current())->get_jni_functions(),sizeof(jniNativeInterface));
3647   return JVMTI_ERROR_NONE;
3648 } /* end GetJNIFunctionTable */
3649 
3650 
3651   //
3652   // Event Management functions
3653   //
3654 
3655 jvmtiError
3656 JvmtiEnv::GenerateEvents(jvmtiEvent event_type) {
3657   // can only generate two event types
3658   if (event_type != JVMTI_EVENT_COMPILED_METHOD_LOAD &&
3659       event_type != JVMTI_EVENT_DYNAMIC_CODE_GENERATED) {
3660     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
3661   }
3662 
3663   // for compiled_method_load events we must check that the environment
3664   // has the can_generate_compiled_method_load_events capability.
3665   if (event_type == JVMTI_EVENT_COMPILED_METHOD_LOAD) {
3666     if (get_capabilities()->can_generate_compiled_method_load_events == 0) {
3667       return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3668     }
3669     return JvmtiCodeBlobEvents::generate_compiled_method_load_events(this);
3670   } else {
3671     return JvmtiCodeBlobEvents::generate_dynamic_code_events(this);
3672   }
3673 
3674 } /* end GenerateEvents */
3675 
3676 
3677   //
3678   // Extension Mechanism functions
3679   //
3680 
3681 // extension_count_ptr - pre-checked for NULL
3682 // extensions - pre-checked for NULL
3683 jvmtiError
3684 JvmtiEnv::GetExtensionFunctions(jint* extension_count_ptr, jvmtiExtensionFunctionInfo** extensions) {
3685   return JvmtiExtensions::get_functions(this, extension_count_ptr, extensions);
3686 } /* end GetExtensionFunctions */
3687 
3688 
3689 // extension_count_ptr - pre-checked for NULL
3690 // extensions - pre-checked for NULL
3691 jvmtiError
3692 JvmtiEnv::GetExtensionEvents(jint* extension_count_ptr, jvmtiExtensionEventInfo** extensions) {
3693   return JvmtiExtensions::get_events(this, extension_count_ptr, extensions);
3694 } /* end GetExtensionEvents */
3695 
3696 
3697 // callback - NULL is a valid value, must be checked
3698 jvmtiError
3699 JvmtiEnv::SetExtensionEventCallback(jint extension_event_index, jvmtiExtensionEvent callback) {
3700   return JvmtiExtensions::set_event_callback(this, extension_event_index, callback);
3701 } /* end SetExtensionEventCallback */
3702 
3703   //
3704   // Timers functions
3705   //
3706 
3707 // info_ptr - pre-checked for NULL
3708 jvmtiError
3709 JvmtiEnv::GetCurrentThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3710   os::current_thread_cpu_time_info(info_ptr);
3711   return JVMTI_ERROR_NONE;
3712 } /* end GetCurrentThreadCpuTimerInfo */
3713 
3714 
3715 // nanos_ptr - pre-checked for NULL
3716 jvmtiError
3717 JvmtiEnv::GetCurrentThreadCpuTime(jlong* nanos_ptr) {
3718   Thread* thread = Thread::current();
3719 
3720   // Surprizingly the GetCurrentThreadCpuTime is used by non-JavaThread's.
3721   if (thread->is_Java_thread()) {
3722     oop thread_obj = get_vthread_or_thread_oop(JavaThread::cast(thread));
3723 
3724     if (java_lang_VirtualThread::is_instance(thread_obj)) {
3725       return JVMTI_ERROR_INVALID_THREAD;
3726     }
3727   }
3728   *nanos_ptr = os::current_thread_cpu_time();
3729   return JVMTI_ERROR_NONE;
3730 } /* end GetCurrentThreadCpuTime */
3731 
3732 
3733 // info_ptr - pre-checked for NULL
3734 jvmtiError
3735 JvmtiEnv::GetThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3736   os::thread_cpu_time_info(info_ptr);
3737   return JVMTI_ERROR_NONE;
3738 } /* end GetThreadCpuTimerInfo */
3739 
3740 
3741 // java_thread - protected by ThreadsListHandle and pre-checked
3742 // nanos_ptr - pre-checked for NULL
3743 jvmtiError
3744 JvmtiEnv::GetThreadCpuTime(JavaThread* java_thread, jlong* nanos_ptr) {
3745   *nanos_ptr = os::thread_cpu_time(java_thread);
3746   return JVMTI_ERROR_NONE;
3747 } /* end GetThreadCpuTime */
3748 
3749 
3750 // info_ptr - pre-checked for NULL
3751 jvmtiError
3752 JvmtiEnv::GetTimerInfo(jvmtiTimerInfo* info_ptr) {
3753   os::javaTimeNanos_info(info_ptr);
3754   return JVMTI_ERROR_NONE;
3755 } /* end GetTimerInfo */
3756 
3757 
3758 // nanos_ptr - pre-checked for NULL
3759 jvmtiError
3760 JvmtiEnv::GetTime(jlong* nanos_ptr) {
3761   *nanos_ptr = os::javaTimeNanos();
3762   return JVMTI_ERROR_NONE;
3763 } /* end GetTime */
3764 
3765 
3766 // processor_count_ptr - pre-checked for NULL
3767 jvmtiError
3768 JvmtiEnv::GetAvailableProcessors(jint* processor_count_ptr) {
3769   *processor_count_ptr = os::active_processor_count();
3770   return JVMTI_ERROR_NONE;
3771 } /* end GetAvailableProcessors */
3772 
3773 jvmtiError
3774 JvmtiEnv::SetHeapSamplingInterval(jint sampling_interval) {
3775   if (sampling_interval < 0) {
3776     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
3777   }
3778   ThreadHeapSampler::set_sampling_interval(sampling_interval);
3779   return JVMTI_ERROR_NONE;
3780 } /* end SetHeapSamplingInterval */
3781 
3782   //
3783   // System Properties functions
3784   //
3785 
3786 // count_ptr - pre-checked for NULL
3787 // property_ptr - pre-checked for NULL
3788 jvmtiError
3789 JvmtiEnv::GetSystemProperties(jint* count_ptr, char*** property_ptr) {
3790   jvmtiError err = JVMTI_ERROR_NONE;
3791 
3792   // Get the number of readable properties.
3793   *count_ptr = Arguments::PropertyList_readable_count(Arguments::system_properties());
3794 
3795   // Allocate memory to hold the exact number of readable properties.
3796   err = allocate(*count_ptr * sizeof(char *), (unsigned char **)property_ptr);
3797   if (err != JVMTI_ERROR_NONE) {
3798     return err;
3799   }
3800   int readable_count = 0;
3801   // Loop through the system properties until all the readable properties are found.
3802   for (SystemProperty* p = Arguments::system_properties(); p != NULL && readable_count < *count_ptr; p = p->next()) {
3803     if (p->is_readable()) {
3804       const char *key = p->key();
3805       char **tmp_value = *property_ptr+readable_count;
3806       readable_count++;
3807       err = allocate((strlen(key)+1) * sizeof(char), (unsigned char**)tmp_value);
3808       if (err == JVMTI_ERROR_NONE) {
3809         strcpy(*tmp_value, key);
3810       } else {
3811         // clean up previously allocated memory.
3812         for (int j = 0; j < readable_count; j++) {
3813           Deallocate((unsigned char*)*property_ptr+j);
3814         }
3815         Deallocate((unsigned char*)property_ptr);
3816         break;
3817       }
3818     }
3819   }
3820   assert(err != JVMTI_ERROR_NONE || readable_count == *count_ptr, "Bad readable property count");
3821   return err;
3822 } /* end GetSystemProperties */
3823 
3824 
3825 // property - pre-checked for NULL
3826 // value_ptr - pre-checked for NULL
3827 jvmtiError
3828 JvmtiEnv::GetSystemProperty(const char* property, char** value_ptr) {
3829   jvmtiError err = JVMTI_ERROR_NONE;
3830   const char *value;
3831 
3832   // Return JVMTI_ERROR_NOT_AVAILABLE if property is not readable or doesn't exist.
3833   value = Arguments::PropertyList_get_readable_value(Arguments::system_properties(), property);
3834   if (value == NULL) {
3835     err =  JVMTI_ERROR_NOT_AVAILABLE;
3836   } else {
3837     err = allocate((strlen(value)+1) * sizeof(char), (unsigned char **)value_ptr);
3838     if (err == JVMTI_ERROR_NONE) {
3839       strcpy(*value_ptr, value);
3840     }
3841   }
3842   return err;
3843 } /* end GetSystemProperty */
3844 
3845 
3846 // property - pre-checked for NULL
3847 // value - NULL is a valid value, must be checked
3848 jvmtiError
3849 JvmtiEnv::SetSystemProperty(const char* property, const char* value_ptr) {
3850   jvmtiError err =JVMTI_ERROR_NOT_AVAILABLE;
3851 
3852   for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
3853     if (strcmp(property, p->key()) == 0) {
3854       if (p->set_writeable_value(value_ptr)) {
3855         err =  JVMTI_ERROR_NONE;
3856       }
3857     }
3858   }
3859   return err;
3860 } /* end SetSystemProperty */