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