1 /*
   2  * Copyright (c) 1997, 2025, 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 "cds/aotConstantPoolResolver.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "cds/classListParser.hpp"
  29 #include "cds/classListWriter.hpp"
  30 #include "cds/dynamicArchive.hpp"
  31 #include "cds/heapShared.hpp"
  32 #include "cds/lambdaFormInvokers.hpp"
  33 #include "classfile/classFileStream.hpp"
  34 #include "classfile/classLoader.inline.hpp"
  35 #include "classfile/classLoaderData.hpp"
  36 #include "classfile/classLoaderData.inline.hpp"
  37 #include "classfile/classLoadInfo.hpp"
  38 #include "classfile/javaAssertions.hpp"
  39 #include "classfile/javaClasses.inline.hpp"
  40 #include "classfile/moduleEntry.hpp"
  41 #include "classfile/modules.hpp"
  42 #include "classfile/packageEntry.hpp"
  43 #include "classfile/stringTable.hpp"
  44 #include "classfile/symbolTable.hpp"
  45 #include "classfile/systemDictionary.hpp"
  46 #include "classfile/vmClasses.hpp"
  47 #include "classfile/vmSymbols.hpp"
  48 #include "gc/shared/collectedHeap.inline.hpp"
  49 #include "interpreter/bytecode.hpp"
  50 #include "interpreter/bytecodeUtils.hpp"
  51 #include "jfr/jfrEvents.hpp"
  52 #include "jvm.h"
  53 #include "logging/log.hpp"
  54 #include "memory/oopFactory.hpp"
  55 #include "memory/referenceType.hpp"
  56 #include "memory/resourceArea.hpp"
  57 #include "memory/universe.hpp"
  58 #include "oops/access.inline.hpp"
  59 #include "oops/constantPool.hpp"
  60 #include "oops/fieldStreams.inline.hpp"
  61 #include "oops/instanceKlass.hpp"
  62 #include "oops/klass.inline.hpp"
  63 #include "oops/method.hpp"
  64 #include "oops/recordComponent.hpp"
  65 #include "oops/objArrayKlass.hpp"
  66 #include "oops/objArrayOop.inline.hpp"
  67 #include "oops/oop.inline.hpp"
  68 #include "prims/foreignGlobals.hpp"
  69 #include "prims/jvm_misc.hpp"
  70 #include "prims/jvmtiExport.hpp"
  71 #include "prims/jvmtiThreadState.inline.hpp"
  72 #include "prims/stackwalk.hpp"
  73 #include "runtime/arguments.hpp"
  74 #include "runtime/atomic.hpp"
  75 #include "runtime/continuation.hpp"
  76 #include "runtime/globals_extension.hpp"
  77 #include "runtime/handles.inline.hpp"
  78 #include "runtime/init.hpp"
  79 #include "runtime/interfaceSupport.inline.hpp"
  80 #include "runtime/deoptimization.hpp"
  81 #include "runtime/handshake.hpp"
  82 #include "runtime/java.hpp"
  83 #include "runtime/javaCalls.hpp"
  84 #include "runtime/javaThread.hpp"
  85 #include "runtime/jfieldIDWorkaround.hpp"
  86 #include "runtime/jniHandles.inline.hpp"
  87 #include "runtime/os.inline.hpp"
  88 #include "runtime/osThread.hpp"
  89 #include "runtime/perfData.inline.hpp"
  90 #include "runtime/reflection.hpp"
  91 #include "runtime/synchronizer.hpp"
  92 #include "runtime/threadIdentifier.hpp"
  93 #include "runtime/threadSMR.hpp"
  94 #include "runtime/vframe.inline.hpp"
  95 #include "runtime/vmOperations.hpp"
  96 #include "runtime/vm_version.hpp"
  97 #include "services/attachListener.hpp"
  98 #include "services/management.hpp"
  99 #include "services/threadService.hpp"
 100 #include "utilities/checkedCast.hpp"
 101 #include "utilities/copy.hpp"
 102 #include "utilities/defaultStream.hpp"
 103 #include "utilities/dtrace.hpp"
 104 #include "utilities/events.hpp"
 105 #include "utilities/macros.hpp"
 106 #include "utilities/utf8.hpp"
 107 #include "utilities/zipLibrary.hpp"
 108 #if INCLUDE_CDS
 109 #include "classfile/systemDictionaryShared.hpp"
 110 #endif
 111 #if INCLUDE_JFR
 112 #include "jfr/jfr.hpp"
 113 #endif
 114 #if INCLUDE_MANAGEMENT
 115 #include "services/finalizerService.hpp"
 116 #endif
 117 #ifdef LINUX
 118 #include "osContainer_linux.hpp"
 119 #endif
 120 
 121 #include <errno.h>
 122 
 123 /*
 124   NOTE about use of any ctor or function call that can trigger a safepoint/GC:
 125   such ctors and calls MUST NOT come between an oop declaration/init and its
 126   usage because if objects are move this may cause various memory stomps, bus
 127   errors and segfaults. Here is a cookbook for causing so called "naked oop
 128   failures":
 129 
 130       JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields<etc> {
 131           // Object address to be held directly in mirror & not visible to GC
 132           oop mirror = JNIHandles::resolve_non_null(ofClass);
 133 
 134           // If this ctor can hit a safepoint, moving objects around, then
 135           ComplexConstructor foo;
 136 
 137           // Boom! mirror may point to JUNK instead of the intended object
 138           (some dereference of mirror)
 139 
 140           // Here's another call that may block for GC, making mirror stale
 141           MutexLocker ml(some_lock);
 142 
 143           // And here's an initializer that can result in a stale oop
 144           // all in one step.
 145           oop o = call_that_can_throw_exception(TRAPS);
 146 
 147 
 148   The solution is to keep the oop declaration BELOW the ctor or function
 149   call that might cause a GC, do another resolve to reassign the oop, or
 150   consider use of a Handle instead of an oop so there is immunity from object
 151   motion. But note that the "QUICK" entries below do not have a handlemark
 152   and thus can only support use of handles passed in.
 153 */
 154 
 155 extern void trace_class_resolution(Klass* to_class) {
 156   ResourceMark rm;
 157   int line_number = -1;
 158   const char * source_file = nullptr;
 159   const char * trace = "explicit";
 160   InstanceKlass* caller = nullptr;
 161   JavaThread* jthread = JavaThread::current();
 162   if (jthread->has_last_Java_frame()) {
 163     vframeStream vfst(jthread);
 164 
 165     // Scan up the stack skipping ClassLoader frames.
 166     Method* last_caller = nullptr;
 167 
 168     while (!vfst.at_end()) {
 169       Method* m = vfst.method();
 170       if (!vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass())) {
 171         break;
 172       }
 173       last_caller = m;
 174       vfst.next();
 175     }
 176     // if this is called from Class.forName0 and that is called from Class.forName,
 177     // then print the caller of Class.forName.  If this is Class.loadClass, then print
 178     // that caller, otherwise keep quiet since this should be picked up elsewhere.
 179     bool found_it = false;
 180     if (!vfst.at_end() &&
 181         vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
 182         vfst.method()->name() == vmSymbols::forName0_name()) {
 183       vfst.next();
 184       if (!vfst.at_end() &&
 185           vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
 186           vfst.method()->name() == vmSymbols::forName_name()) {
 187         vfst.next();
 188         found_it = true;
 189       }
 190     } else if (last_caller != nullptr &&
 191                last_caller->method_holder()->name() ==
 192                  vmSymbols::java_lang_ClassLoader() &&
 193                last_caller->name() == vmSymbols::loadClass_name()) {
 194       found_it = true;
 195     } else if (!vfst.at_end()) {
 196       if (vfst.method()->is_native()) {
 197         // JNI call
 198         found_it = true;
 199       }
 200     }
 201     if (found_it && !vfst.at_end()) {
 202       // found the caller
 203       caller = vfst.method()->method_holder();
 204       line_number = vfst.method()->line_number_from_bci(vfst.bci());
 205       if (line_number == -1) {
 206         // show method name if it's a native method
 207         trace = vfst.method()->name_and_sig_as_C_string();
 208       }
 209       Symbol* s = caller->source_file_name();
 210       if (s != nullptr) {
 211         source_file = s->as_C_string();
 212       }
 213     }
 214   }
 215   if (caller != nullptr) {
 216     if (to_class != caller) {
 217       const char * from = caller->external_name();
 218       const char * to = to_class->external_name();
 219       // print in a single call to reduce interleaving between threads
 220       if (source_file != nullptr) {
 221         log_debug(class, resolve)("%s %s %s:%d (%s)", from, to, source_file, line_number, trace);
 222       } else {
 223         log_debug(class, resolve)("%s %s (%s)", from, to, trace);
 224       }
 225     }
 226   }
 227 }
 228 
 229 // java.lang.System //////////////////////////////////////////////////////////////////////
 230 
 231 
 232 JVM_LEAF_PROF(jboolean, JVM_AOTIsTraining, JVM_AOTIsTraining(JNIEnv *env))
 233 #if INCLUDE_CDS
 234   return MetaspaceShared::is_recording_preimage_static_archive();
 235 #else
 236   return JNI_FALSE;
 237 #endif // INCLUDE_CDS
 238 JVM_END
 239 
 240 JVM_ENTRY_PROF(void, JVM_AOTEndTraining, JVM_AOTEndTraining(JNIEnv *env))
 241 #if INCLUDE_CDS
 242   if (MetaspaceShared::is_recording_preimage_static_archive()) {
 243     MetaspaceShared::preload_and_dump(THREAD);
 244   }
 245 #endif // INCLUDE_CDS
 246 JVM_END
 247 
 248 JVM_LEAF_PROF(jlong, JVM_CurrentTimeMillis, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))
 249   return os::javaTimeMillis();
 250 JVM_END
 251 
 252 JVM_LEAF_PROF(jlong, JVM_NanoTime, JVM_NanoTime(JNIEnv *env, jclass ignored))
 253   return os::javaTimeNanos();
 254 JVM_END
 255 
 256 // The function below is actually exposed by jdk.internal.misc.VM and not
 257 // java.lang.System, but we choose to keep it here so that it stays next
 258 // to JVM_CurrentTimeMillis and JVM_NanoTime
 259 
 260 const jlong MAX_DIFF_SECS = CONST64(0x0100000000); //  2^32
 261 const jlong MIN_DIFF_SECS = -MAX_DIFF_SECS; // -2^32
 262 
 263 JVM_LEAF_PROF(jlong, JVM_GetNanoTimeAdjustment, JVM_GetNanoTimeAdjustment(JNIEnv *env, jclass ignored, jlong offset_secs))
 264   jlong seconds;
 265   jlong nanos;
 266 
 267   os::javaTimeSystemUTC(seconds, nanos);
 268 
 269   // We're going to verify that the result can fit in a long.
 270   // For that we need the difference in seconds between 'seconds'
 271   // and 'offset_secs' to be such that:
 272   //     |seconds - offset_secs| < (2^63/10^9)
 273   // We're going to approximate 10^9 ~< 2^30 (1000^3 ~< 1024^3)
 274   // which makes |seconds - offset_secs| < 2^33
 275   // and we will prefer +/- 2^32 as the maximum acceptable diff
 276   // as 2^32 has a more natural feel than 2^33...
 277   //
 278   // So if |seconds - offset_secs| >= 2^32 - we return a special
 279   // sentinel value (-1) which the caller should take as an
 280   // exception value indicating that the offset given to us is
 281   // too far from range of the current time - leading to too big
 282   // a nano adjustment. The caller is expected to recover by
 283   // computing a more accurate offset and calling this method
 284   // again. (For the record 2^32 secs is ~136 years, so that
 285   // should rarely happen)
 286   //
 287   jlong diff = seconds - offset_secs;
 288   if (diff >= MAX_DIFF_SECS || diff <= MIN_DIFF_SECS) {
 289      return -1; // sentinel value: the offset is too far off the target
 290   }
 291 
 292   // return the adjustment. If you compute a time by adding
 293   // this number of nanoseconds along with the number of seconds
 294   // in the offset you should get the current UTC time.
 295   return (diff * (jlong)1000000000) + nanos;
 296 JVM_END
 297 
 298 JVM_ENTRY_PROF(void, JVM_ArrayCopy, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos,
 299                                jobject dst, jint dst_pos, jint length))
 300   // Check if we have null pointers
 301   if (src == nullptr || dst == nullptr) {
 302     THROW(vmSymbols::java_lang_NullPointerException());
 303   }
 304   arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
 305   arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
 306   assert(oopDesc::is_oop(s), "JVM_ArrayCopy: src not an oop");
 307   assert(oopDesc::is_oop(d), "JVM_ArrayCopy: dst not an oop");
 308   // Do copy
 309   s->klass()->copy_array(s, src_pos, d, dst_pos, length, thread);
 310 JVM_END
 311 
 312 
 313 static void set_property(Handle props, const char* key, const char* value, TRAPS) {
 314   JavaValue r(T_OBJECT);
 315   // public synchronized Object put(Object key, Object value);
 316   HandleMark hm(THREAD);
 317   Handle key_str    = java_lang_String::create_from_platform_dependent_str(key, CHECK);
 318   Handle value_str  = java_lang_String::create_from_platform_dependent_str((value != nullptr ? value : ""), CHECK);
 319   JavaCalls::call_virtual(&r,
 320                           props,
 321                           vmClasses::Properties_klass(),
 322                           vmSymbols::put_name(),
 323                           vmSymbols::object_object_object_signature(),
 324                           key_str,
 325                           value_str,
 326                           THREAD);
 327 }
 328 
 329 
 330 #define PUTPROP(props, name, value) set_property((props), (name), (value), CHECK_(properties));
 331 
 332 /*
 333  * Return all of the system properties in a Java String array with alternating
 334  * names and values from the jvm SystemProperty.
 335  * Which includes some internal and all commandline -D defined properties.
 336  */
 337 JVM_ENTRY_PROF(jobjectArray, JVM_GetProperties, JVM_GetProperties(JNIEnv *env))
 338   ResourceMark rm(THREAD);
 339   HandleMark hm(THREAD);
 340   int ndx = 0;
 341   int fixedCount = 2;
 342 
 343   SystemProperty* p = Arguments::system_properties();
 344   int count = Arguments::PropertyList_count(p);
 345 
 346   // Allocate result String array
 347   InstanceKlass* ik = vmClasses::String_klass();
 348   objArrayOop r = oopFactory::new_objArray(ik, (count + fixedCount) * 2, CHECK_NULL);
 349   objArrayHandle result_h(THREAD, r);
 350 
 351   while (p != nullptr) {
 352     const char * key = p->key();
 353     if (strcmp(key, "sun.nio.MaxDirectMemorySize") != 0) {
 354         const char * value = p->value();
 355         Handle key_str    = java_lang_String::create_from_platform_dependent_str(key, CHECK_NULL);
 356         Handle value_str  = java_lang_String::create_from_platform_dependent_str((value != nullptr ? value : ""), CHECK_NULL);
 357         result_h->obj_at_put(ndx * 2,  key_str());
 358         result_h->obj_at_put(ndx * 2 + 1, value_str());
 359         ndx++;
 360     }
 361     p = p->next();
 362   }
 363 
 364   // Convert the -XX:MaxDirectMemorySize= command line flag
 365   // to the sun.nio.MaxDirectMemorySize property.
 366   // Do this after setting user properties to prevent people
 367   // from setting the value with a -D option, as requested.
 368   // Leave empty if not supplied
 369   if (!FLAG_IS_DEFAULT(MaxDirectMemorySize)) {
 370     char as_chars[256];
 371     jio_snprintf(as_chars, sizeof(as_chars), JULONG_FORMAT, MaxDirectMemorySize);
 372     Handle key_str = java_lang_String::create_from_platform_dependent_str("sun.nio.MaxDirectMemorySize", CHECK_NULL);
 373     Handle value_str  = java_lang_String::create_from_platform_dependent_str(as_chars, CHECK_NULL);
 374     result_h->obj_at_put(ndx * 2,  key_str());
 375     result_h->obj_at_put(ndx * 2 + 1, value_str());
 376     ndx++;
 377   }
 378 
 379   // JVM monitoring and management support
 380   // Add the sun.management.compiler property for the compiler's name
 381   {
 382 #undef CSIZE
 383 #if defined(_LP64)
 384   #define CSIZE "64-Bit "
 385 #else
 386   #define CSIZE
 387 #endif // 64bit
 388 
 389 #if COMPILER1_AND_COMPILER2
 390     const char* compiler_name = "HotSpot " CSIZE "Tiered Compilers";
 391 #else
 392 #if defined(COMPILER1)
 393     const char* compiler_name = "HotSpot " CSIZE "Client Compiler";
 394 #elif defined(COMPILER2)
 395     const char* compiler_name = "HotSpot " CSIZE "Server Compiler";
 396 #elif INCLUDE_JVMCI
 397     #error "INCLUDE_JVMCI should imply COMPILER1_OR_COMPILER2"
 398 #else
 399     const char* compiler_name = "";
 400 #endif // compilers
 401 #endif // COMPILER1_AND_COMPILER2
 402 
 403     if (*compiler_name != '\0' &&
 404         (Arguments::mode() != Arguments::_int)) {
 405       Handle key_str = java_lang_String::create_from_platform_dependent_str("sun.management.compiler", CHECK_NULL);
 406       Handle value_str  = java_lang_String::create_from_platform_dependent_str(compiler_name, CHECK_NULL);
 407       result_h->obj_at_put(ndx * 2,  key_str());
 408       result_h->obj_at_put(ndx * 2 + 1, value_str());
 409       ndx++;
 410     }
 411   }
 412 
 413   return (jobjectArray) JNIHandles::make_local(THREAD, result_h());
 414 JVM_END
 415 
 416 
 417 /*
 418  * Return the temporary directory that the VM uses for the attach
 419  * and perf data files.
 420  *
 421  * It is important that this directory is well-known and the
 422  * same for all VM instances. It cannot be affected by configuration
 423  * variables such as java.io.tmpdir.
 424  */
 425 JVM_ENTRY_PROF(jstring, JVM_GetTemporaryDirectory, JVM_GetTemporaryDirectory(JNIEnv *env))
 426   HandleMark hm(THREAD);
 427   const char* temp_dir = os::get_temp_directory();
 428   Handle h = java_lang_String::create_from_platform_dependent_str(temp_dir, CHECK_NULL);
 429   return (jstring) JNIHandles::make_local(THREAD, h());
 430 JVM_END
 431 
 432 
 433 // java.lang.Runtime /////////////////////////////////////////////////////////////////////////
 434 
 435 extern volatile jint vm_created;
 436 
 437 JVM_ENTRY_NO_ENV_PROF(void, JVM_BeforeHalt, JVM_BeforeHalt())
 438   EventShutdown event;
 439   if (event.should_commit()) {
 440     event.set_reason("Shutdown requested from Java");
 441     event.commit();
 442   }
 443 JVM_END
 444 
 445 
 446 JVM_ENTRY_NO_ENV_PROF(void, JVM_Halt, JVM_Halt(jint code))
 447   before_exit(thread, true);
 448   vm_exit(code);
 449 JVM_END
 450 
 451 
 452 JVM_ENTRY_NO_ENV_PROF(void, JVM_GC, JVM_GC(void))
 453   if (!DisableExplicitGC) {
 454     EventSystemGC event;
 455     event.set_invokedConcurrent(ExplicitGCInvokesConcurrent);
 456     Universe::heap()->collect(GCCause::_java_lang_system_gc);
 457     event.commit();
 458   }
 459 JVM_END
 460 
 461 
 462 JVM_LEAF_PROF(jlong, JVM_MaxObjectInspectionAge, JVM_MaxObjectInspectionAge(void))
 463   return Universe::heap()->millis_since_last_whole_heap_examined();
 464 JVM_END
 465 
 466 
 467 static inline jlong convert_size_t_to_jlong(size_t val) {
 468   // In the 64-bit vm, a size_t can overflow a jlong (which is signed).
 469   NOT_LP64 (return (jlong)val;)
 470   LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)
 471 }
 472 
 473 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_TotalMemory, JVM_TotalMemory(void))
 474   size_t n = Universe::heap()->capacity();
 475   return convert_size_t_to_jlong(n);
 476 JVM_END
 477 
 478 
 479 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_FreeMemory, JVM_FreeMemory(void))
 480   size_t n = Universe::heap()->unused();
 481   return convert_size_t_to_jlong(n);
 482 JVM_END
 483 
 484 
 485 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_MaxMemory, JVM_MaxMemory(void))
 486   size_t n = Universe::heap()->max_capacity();
 487   return convert_size_t_to_jlong(n);
 488 JVM_END
 489 
 490 
 491 JVM_ENTRY_NO_ENV_PROF(jint, JVM_ActiveProcessorCount, JVM_ActiveProcessorCount(void))
 492   return os::active_processor_count();
 493 JVM_END
 494 
 495 JVM_LEAF_PROF(jboolean, JVM_IsUseContainerSupport, JVM_IsUseContainerSupport(void))
 496 #ifdef LINUX
 497   if (UseContainerSupport) {
 498     return JNI_TRUE;
 499   }
 500 #endif
 501   return JNI_FALSE;
 502 JVM_END
 503 
 504 JVM_LEAF(jboolean, JVM_IsContainerized(void))
 505 #ifdef LINUX
 506   if (OSContainer::is_containerized()) {
 507     return JNI_TRUE;
 508   }
 509 #endif
 510   return JNI_FALSE;
 511 JVM_END
 512 
 513 // java.lang.Throwable //////////////////////////////////////////////////////
 514 
 515 JVM_ENTRY_PROF(void, JVM_FillInStackTrace, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))
 516   Handle exception(thread, JNIHandles::resolve_non_null(receiver));
 517   java_lang_Throwable::fill_in_stack_trace(exception);
 518 JVM_END
 519 
 520 // java.lang.NullPointerException ///////////////////////////////////////////
 521 
 522 JVM_ENTRY_PROF(jstring, JVM_GetExtendedNPEMessage, JVM_GetExtendedNPEMessage(JNIEnv *env, jthrowable throwable))
 523   if (!ShowCodeDetailsInExceptionMessages) return nullptr;
 524 
 525   oop exc = JNIHandles::resolve_non_null(throwable);
 526 
 527   Method* method;
 528   int bci;
 529   if (!java_lang_Throwable::get_top_method_and_bci(exc, &method, &bci)) {
 530     return nullptr;
 531   }
 532   if (method->is_native()) {
 533     return nullptr;
 534   }
 535 
 536   stringStream ss;
 537   bool ok = BytecodeUtils::get_NPE_message_at(&ss, method, bci);
 538   if (ok) {
 539     oop result = java_lang_String::create_oop_from_str(ss.base(), CHECK_NULL);
 540     return (jstring) JNIHandles::make_local(THREAD, result);
 541   } else {
 542     return nullptr;
 543   }
 544 JVM_END
 545 
 546 // java.lang.StackTraceElement //////////////////////////////////////////////
 547 
 548 
 549 JVM_ENTRY_PROF(void, JVM_InitStackTraceElementArray, JVM_InitStackTraceElementArray(JNIEnv *env, jobjectArray elements, jobject backtrace, jint depth))
 550   Handle backtraceh(THREAD, JNIHandles::resolve(backtrace));
 551   objArrayOop st = objArrayOop(JNIHandles::resolve(elements));
 552   objArrayHandle stack_trace(THREAD, st);
 553   // Fill in the allocated stack trace
 554   java_lang_Throwable::get_stack_trace_elements(depth, backtraceh, stack_trace, CHECK);
 555 JVM_END
 556 
 557 
 558 JVM_ENTRY_PROF(void, JVM_InitStackTraceElement, JVM_InitStackTraceElement(JNIEnv* env, jobject element, jobject stackFrameInfo))
 559   Handle stack_frame_info(THREAD, JNIHandles::resolve_non_null(stackFrameInfo));
 560   Handle stack_trace_element(THREAD, JNIHandles::resolve_non_null(element));
 561   java_lang_StackFrameInfo::to_stack_trace_element(stack_frame_info, stack_trace_element, CHECK);
 562 JVM_END
 563 
 564 
 565 // java.lang.StackWalker //////////////////////////////////////////////////////
 566 JVM_ENTRY_PROF(void, JVM_ExpandStackFrameInfo, JVM_ExpandStackFrameInfo(JNIEnv *env, jobject obj))
 567   Handle stack_frame_info(THREAD, JNIHandles::resolve_non_null(obj));
 568 
 569   bool have_name = (java_lang_StackFrameInfo::name(stack_frame_info()) != nullptr);
 570   bool have_type = (java_lang_StackFrameInfo::type(stack_frame_info()) != nullptr);
 571   Method* method = java_lang_StackFrameInfo::get_method(stack_frame_info());
 572   if (!have_name) {
 573     oop name = StringTable::intern(method->name(), CHECK);
 574     java_lang_StackFrameInfo::set_name(stack_frame_info(), name);
 575   }
 576   if (!have_type) {
 577     Handle type = java_lang_String::create_from_symbol(method->signature(), CHECK);
 578     java_lang_StackFrameInfo::set_type(stack_frame_info(), type());
 579   }
 580 JVM_END
 581 
 582 JVM_ENTRY_PROF(jobject, JVM_CallStackWalk, JVM_CallStackWalk(JNIEnv *env, jobject stackStream, jint mode,
 583                                                          jint skip_frames, jobject contScope, jobject cont,
 584                                                          jint buffer_size, jint start_index, jobjectArray frames))
 585   if (!thread->has_last_Java_frame()) {
 586     THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: no stack trace", nullptr);
 587   }
 588 
 589   Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
 590   Handle contScope_h(THREAD, JNIHandles::resolve(contScope));
 591   Handle cont_h(THREAD, JNIHandles::resolve(cont));
 592   // frames array is a ClassFrameInfo[] array when only getting caller reference,
 593   // and a StackFrameInfo[] array (or derivative) otherwise. It should never
 594   // be null.
 595   objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
 596   objArrayHandle frames_array_h(THREAD, fa);
 597 
 598   if (frames_array_h->length() < buffer_size) {
 599     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers", nullptr);
 600   }
 601 
 602   oop result = StackWalk::walk(stackStream_h, mode, skip_frames, contScope_h, cont_h,
 603                                buffer_size, start_index, frames_array_h, CHECK_NULL);
 604   return JNIHandles::make_local(THREAD, result);
 605 JVM_END
 606 
 607 
 608 JVM_ENTRY_PROF(jint, JVM_MoreStackWalk, JVM_MoreStackWalk(JNIEnv *env, jobject stackStream, jint mode, jlong anchor,
 609                                                       jint last_batch_count, jint buffer_size, jint start_index,
 610                                                       jobjectArray frames))
 611   // frames array is a ClassFrameInfo[] array when only getting caller reference,
 612   // and a StackFrameInfo[] array (or derivative) otherwise. It should never
 613   // be null.
 614   objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
 615   objArrayHandle frames_array_h(THREAD, fa);
 616 
 617   if (frames_array_h->length() < buffer_size) {
 618     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers");
 619   }
 620 
 621   Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
 622   return StackWalk::fetchNextBatch(stackStream_h, mode, anchor, last_batch_count, buffer_size,
 623                                   start_index, frames_array_h, THREAD);
 624 JVM_END
 625 
 626 JVM_ENTRY_PROF(void, JVM_SetStackWalkContinuation, JVM_SetStackWalkContinuation(JNIEnv *env, jobject stackStream, jlong anchor, jobjectArray frames, jobject cont))
 627   objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
 628   objArrayHandle frames_array_h(THREAD, fa);
 629   Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
 630   Handle cont_h(THREAD, JNIHandles::resolve_non_null(cont));
 631 
 632   StackWalk::setContinuation(stackStream_h, anchor, frames_array_h, cont_h, THREAD);
 633 JVM_END
 634 
 635 // java.lang.Object ///////////////////////////////////////////////
 636 
 637 
 638 JVM_ENTRY_PROF(jint, JVM_IHashCode, JVM_IHashCode(JNIEnv* env, jobject handle))
 639   // as implemented in the classic virtual machine; return 0 if object is null
 640   return handle == nullptr ? 0 :
 641          checked_cast<jint>(ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)));
 642 JVM_END
 643 
 644 
 645 JVM_ENTRY_PROF(void, JVM_MonitorWait, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
 646   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 647   JavaThreadInObjectWaitState jtiows(thread, ms != 0);
 648   if (JvmtiExport::should_post_monitor_wait()) {
 649     JvmtiExport::post_monitor_wait(thread, obj(), ms);
 650 
 651     // The current thread already owns the monitor and it has not yet
 652     // been added to the wait queue so the current thread cannot be
 653     // made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT
 654     // event handler cannot accidentally consume an unpark() meant for
 655     // the ParkEvent associated with this ObjectMonitor.
 656   }
 657   ObjectSynchronizer::wait(obj, ms, CHECK);
 658 JVM_END
 659 
 660 
 661 JVM_ENTRY_PROF(void, JVM_MonitorNotify, JVM_MonitorNotify(JNIEnv* env, jobject handle))
 662   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 663   ObjectSynchronizer::notify(obj, CHECK);
 664 JVM_END
 665 
 666 
 667 JVM_ENTRY_PROF(void, JVM_MonitorNotifyAll, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))
 668   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 669   ObjectSynchronizer::notifyall(obj, CHECK);
 670 JVM_END
 671 
 672 
 673 JVM_ENTRY_PROF(jobject, JVM_Clone, JVM_Clone(JNIEnv* env, jobject handle))
 674   Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
 675   Klass* klass = obj->klass();
 676   JvmtiVMObjectAllocEventCollector oam;
 677 
 678 #ifdef ASSERT
 679   // Just checking that the cloneable flag is set correct
 680   if (obj->is_array()) {
 681     guarantee(klass->is_cloneable(), "all arrays are cloneable");
 682   } else {
 683     guarantee(obj->is_instance(), "should be instanceOop");
 684     bool cloneable = klass->is_subtype_of(vmClasses::Cloneable_klass());
 685     guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");
 686   }
 687 #endif
 688 
 689   // Check if class of obj supports the Cloneable interface.
 690   // All arrays are considered to be cloneable (See JLS 20.1.5).
 691   // All j.l.r.Reference classes are considered non-cloneable.
 692   if (!klass->is_cloneable() ||
 693       (klass->is_instance_klass() &&
 694        InstanceKlass::cast(klass)->reference_type() != REF_NONE)) {
 695     ResourceMark rm(THREAD);
 696     THROW_MSG_NULL(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
 697   }
 698 
 699   // Make shallow object copy
 700   const size_t size = obj->size();
 701   oop new_obj_oop = nullptr;
 702   if (obj->is_array()) {
 703     const int length = ((arrayOop)obj())->length();
 704     new_obj_oop = Universe::heap()->array_allocate(klass, size, length,
 705                                                    /* do_zero */ true, CHECK_NULL);
 706   } else {
 707     new_obj_oop = Universe::heap()->obj_allocate(klass, size, CHECK_NULL);
 708   }
 709 
 710   HeapAccess<>::clone(obj(), new_obj_oop, size);
 711 
 712   Handle new_obj(THREAD, new_obj_oop);
 713   // Caution: this involves a java upcall, so the clone should be
 714   // "gc-robust" by this stage.
 715   if (klass->has_finalizer()) {
 716     assert(obj->is_instance(), "should be instanceOop");
 717     new_obj_oop = InstanceKlass::register_finalizer(instanceOop(new_obj()), CHECK_NULL);
 718     new_obj = Handle(THREAD, new_obj_oop);
 719   }
 720 
 721   return JNIHandles::make_local(THREAD, new_obj());
 722 JVM_END
 723 
 724 // java.lang.ref.Finalizer ////////////////////////////////////////////////////
 725 
 726 JVM_ENTRY_PROF(void, JVM_ReportFinalizationComplete, JVM_ReportFinalizationComplete(JNIEnv * env, jobject finalizee))
 727   MANAGEMENT_ONLY(FinalizerService::on_complete(JNIHandles::resolve_non_null(finalizee), THREAD);)
 728 JVM_END
 729 
 730 JVM_LEAF_PROF(jboolean, JVM_IsFinalizationEnabled, JVM_IsFinalizationEnabled(JNIEnv * env))
 731   return InstanceKlass::is_finalization_enabled();
 732 JVM_END
 733 
 734 // jdk.internal.vm.Continuation /////////////////////////////////////////////////////
 735 
 736 JVM_ENTRY_PROF(void, JVM_RegisterContinuationMethods, JVM_RegisterContinuationMethods(JNIEnv *env, jclass cls))
 737   CONT_RegisterNativeMethods(env, cls);
 738 JVM_END
 739 
 740 // java.io.File ///////////////////////////////////////////////////////////////
 741 
 742 JVM_LEAF_PROF(char*, JVM_NativePath, JVM_NativePath(char* path))
 743   return os::native_path(path);
 744 JVM_END
 745 
 746 
 747 // Misc. class handling ///////////////////////////////////////////////////////////
 748 
 749 
 750 JVM_ENTRY_PROF(jclass, JVM_GetCallerClass, JVM_GetCallerClass(JNIEnv* env))
 751   // Getting the class of the caller frame.
 752   //
 753   // The call stack at this point looks something like this:
 754   //
 755   // [0] [ @CallerSensitive public jdk.internal.reflect.Reflection.getCallerClass ]
 756   // [1] [ @CallerSensitive API.method                                   ]
 757   // [.] [ (skipped intermediate frames)                                 ]
 758   // [n] [ caller                                                        ]
 759   vframeStream vfst(thread);
 760   // Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
 761   for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
 762     Method* m = vfst.method();
 763     assert(m != nullptr, "sanity");
 764     switch (n) {
 765     case 0:
 766       // This must only be called from Reflection.getCallerClass
 767       if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
 768         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
 769       }
 770       // fall-through
 771     case 1:
 772       // Frame 0 and 1 must be caller sensitive.
 773       if (!m->caller_sensitive()) {
 774         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
 775       }
 776       break;
 777     default:
 778       if (!m->is_ignored_by_security_stack_walk()) {
 779         // We have reached the desired frame; return the holder class.
 780         return (jclass) JNIHandles::make_local(THREAD, m->method_holder()->java_mirror());
 781       }
 782       break;
 783     }
 784   }
 785   return nullptr;
 786 JVM_END
 787 
 788 
 789 JVM_ENTRY_PROF(jclass, JVM_FindPrimitiveClass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
 790   oop mirror = nullptr;
 791   BasicType t = name2type(utf);
 792   if (t != T_ILLEGAL && !is_reference_type(t)) {
 793     mirror = Universe::java_mirror(t);
 794   }
 795   if (mirror == nullptr) {
 796     THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
 797   } else {
 798     return (jclass) JNIHandles::make_local(THREAD, mirror);
 799   }
 800 JVM_END
 801 
 802 
 803 // Returns a class loaded by the bootstrap class loader; or null
 804 // if not found.  ClassNotFoundException is not thrown.
 805 // FindClassFromBootLoader is exported to the launcher for windows.
 806 JVM_ENTRY_PROF(jclass, JVM_FindClassFromBootLoader, JVM_FindClassFromBootLoader(JNIEnv* env, const char* name))
 807   // Java libraries should ensure that name is never null or illegal.
 808   if (name == nullptr || (int)strlen(name) > Symbol::max_length()) {
 809     // It's impossible to create this class;  the name cannot fit
 810     // into the constant pool.
 811     return nullptr;
 812   }
 813   assert(UTF8::is_legal_utf8((const unsigned char*)name, strlen(name), false), "illegal UTF name");
 814 
 815   TempNewSymbol h_name = SymbolTable::new_symbol(name);
 816   Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
 817   if (k == nullptr) {
 818     return nullptr;
 819   }
 820 
 821   if (log_is_enabled(Debug, class, resolve)) {
 822     trace_class_resolution(k);
 823   }
 824   return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
 825 JVM_END
 826 
 827 // Find a class with this name in this loader, using the caller's protection domain.
 828 JVM_ENTRY_PROF(jclass, JVM_FindClassFromCaller, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
 829                                                                    jboolean init, jobject loader,
 830                                                                    jclass caller))
 831   TempNewSymbol h_name =
 832        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_ClassNotFoundException(),
 833                                            CHECK_NULL);
 834 
 835   oop loader_oop = JNIHandles::resolve(loader);
 836   oop from_class = JNIHandles::resolve(caller);
 837   Handle h_loader(THREAD, loader_oop);
 838 
 839   jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
 840                                                false, THREAD);
 841 
 842   if (log_is_enabled(Debug, class, resolve) && result != nullptr) {
 843     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
 844   }
 845   return result;
 846 JVM_END
 847 
 848 // Currently only called from the old verifier.
 849 JVM_ENTRY_PROF(jclass, JVM_FindClassFromClass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
 850                                                                  jboolean init, jclass from))
 851   TempNewSymbol h_name =
 852        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_ClassNotFoundException(),
 853                                            CHECK_NULL);
 854   oop from_class_oop = JNIHandles::resolve(from);
 855   Klass* from_class = (from_class_oop == nullptr)
 856                            ? (Klass*)nullptr
 857                            : java_lang_Class::as_Klass(from_class_oop);
 858   oop class_loader = nullptr;
 859   if (from_class != nullptr) {
 860     class_loader = from_class->class_loader();
 861   }
 862   Handle h_loader(THREAD, class_loader);
 863   jclass result = find_class_from_class_loader(env, h_name, init, h_loader, true, thread);
 864 
 865   if (log_is_enabled(Debug, class, resolve) && result != nullptr) {
 866     // this function is generally only used for class loading during verification.
 867     ResourceMark rm;
 868     oop from_mirror = JNIHandles::resolve_non_null(from);
 869     Klass* from_class = java_lang_Class::as_Klass(from_mirror);
 870     const char * from_name = from_class->external_name();
 871 
 872     oop mirror = JNIHandles::resolve_non_null(result);
 873     Klass* to_class = java_lang_Class::as_Klass(mirror);
 874     const char * to = to_class->external_name();
 875     log_debug(class, resolve)("%s %s (verification)", from_name, to);
 876   }
 877 
 878   return result;
 879 JVM_END
 880 
 881 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
 882 static jclass jvm_define_class_common(const char *name,
 883                                       jobject loader, const jbyte *buf,
 884                                       jsize len, jobject pd, const char *source,
 885                                       TRAPS) {
 886   if (source == nullptr)  source = "__JVM_DefineClass__";
 887 
 888   JavaThread* jt = THREAD;
 889 
 890   PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
 891                              ClassLoader::perf_define_appclass_selftime(),
 892                              ClassLoader::perf_define_appclasses(),
 893                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 894                              jt->get_thread_stat()->perf_timers_addr(),
 895                              PerfClassTraceTime::DEFINE_CLASS);
 896 
 897   if (UsePerfData) {
 898     ClassLoader::perf_app_classfile_bytes_read()->inc(len);
 899   }
 900 
 901   // Class resolution will get the class name from the .class stream if the name is null.
 902   TempNewSymbol class_name = name == nullptr ? nullptr :
 903        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_NoClassDefFoundError(),
 904                                            CHECK_NULL);
 905 
 906   ResourceMark rm(THREAD);
 907   ClassFileStream st((u1*)buf, len, source);
 908   Handle class_loader (THREAD, JNIHandles::resolve(loader));
 909   Handle protection_domain (THREAD, JNIHandles::resolve(pd));
 910   ClassLoadInfo cl_info(protection_domain);
 911   Klass* k = SystemDictionary::resolve_from_stream(&st, class_name,
 912                                                    class_loader,
 913                                                    cl_info,
 914                                                    CHECK_NULL);
 915 
 916   if (log_is_enabled(Debug, class, resolve)) {
 917     trace_class_resolution(k);
 918   }
 919 
 920   return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
 921 }
 922 
 923 enum {
 924   NESTMATE              = java_lang_invoke_MemberName::MN_NESTMATE_CLASS,
 925   HIDDEN_CLASS          = java_lang_invoke_MemberName::MN_HIDDEN_CLASS,
 926   STRONG_LOADER_LINK    = java_lang_invoke_MemberName::MN_STRONG_LOADER_LINK,
 927   ACCESS_VM_ANNOTATIONS = java_lang_invoke_MemberName::MN_ACCESS_VM_ANNOTATIONS
 928 };
 929 
 930 /*
 931  * Define a class with the specified flags that indicates if it's a nestmate,
 932  * hidden, or strongly referenced from class loader.
 933  */
 934 static jclass jvm_lookup_define_class(jclass lookup, const char *name,
 935                                       const jbyte *buf, jsize len, jobject pd,
 936                                       jboolean init, int flags, jobject classData, TRAPS) {
 937   ResourceMark rm(THREAD);
 938 
 939   Klass* lookup_k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(lookup));
 940   // Lookup class must be a non-null instance
 941   if (lookup_k == nullptr) {
 942     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class is null");
 943   }
 944   assert(lookup_k->is_instance_klass(), "Lookup class must be an instance klass");
 945 
 946   Handle class_loader (THREAD, lookup_k->class_loader());
 947 
 948   bool is_nestmate = (flags & NESTMATE) == NESTMATE;
 949   bool is_hidden = (flags & HIDDEN_CLASS) == HIDDEN_CLASS;
 950   bool is_strong = (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK;
 951   bool vm_annotations = (flags & ACCESS_VM_ANNOTATIONS) == ACCESS_VM_ANNOTATIONS;
 952 
 953   InstanceKlass* host_class = nullptr;
 954   if (is_nestmate) {
 955     host_class = InstanceKlass::cast(lookup_k)->nest_host(CHECK_NULL);
 956   }
 957 
 958   log_info(class, nestmates)("LookupDefineClass: %s - %s%s, %s, %s, %s",
 959                              name,
 960                              is_nestmate ? "with dynamic nest-host " : "non-nestmate",
 961                              is_nestmate ? host_class->external_name() : "",
 962                              is_hidden ? "hidden" : "not hidden",
 963                              is_strong ? "strong" : "weak",
 964                              vm_annotations ? "with vm annotations" : "without vm annotation");
 965 
 966   if (!is_hidden) {
 967     // classData is only applicable for hidden classes
 968     if (classData != nullptr) {
 969       THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "classData is only applicable for hidden classes");
 970     }
 971     if (is_nestmate) {
 972       THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "dynamic nestmate is only applicable for hidden classes");
 973     }
 974     if (!is_strong) {
 975       THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "an ordinary class must be strongly referenced by its defining loader");
 976     }
 977     if (vm_annotations) {
 978       THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "vm annotations only allowed for hidden classes");
 979     }
 980     if (flags != STRONG_LOADER_LINK) {
 981       THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
 982                      err_msg("invalid flag 0x%x", flags));
 983     }
 984   }
 985 
 986   // Class resolution will get the class name from the .class stream if the name is null.
 987   TempNewSymbol class_name = name == nullptr ? nullptr :
 988        SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_NoClassDefFoundError(),
 989                                            CHECK_NULL);
 990 
 991   Handle protection_domain (THREAD, JNIHandles::resolve(pd));
 992   const char* source = is_nestmate ? host_class->external_name() : "__JVM_LookupDefineClass__";
 993   ClassFileStream st((u1*)buf, len, source);
 994 
 995   InstanceKlass* ik = nullptr;
 996   if (!is_hidden) {
 997     ClassLoadInfo cl_info(protection_domain);
 998     ik = SystemDictionary::resolve_from_stream(&st, class_name,
 999                                                class_loader,
1000                                                cl_info,
1001                                                CHECK_NULL);
1002 
1003     if (log_is_enabled(Debug, class, resolve)) {
1004       trace_class_resolution(ik);
1005     }
1006   } else { // hidden
1007     Handle classData_h(THREAD, JNIHandles::resolve(classData));
1008     ClassLoadInfo cl_info(protection_domain,
1009                           host_class,
1010                           classData_h,
1011                           is_hidden,
1012                           is_strong,
1013                           vm_annotations);
1014     ik = SystemDictionary::resolve_from_stream(&st, class_name,
1015                                                class_loader,
1016                                                cl_info,
1017                                                CHECK_NULL);
1018 
1019     // The hidden class loader data has been artificially been kept alive to
1020     // this point. The mirror and any instances of this class have to keep
1021     // it alive afterwards.
1022     ik->class_loader_data()->dec_keep_alive_ref_count();
1023 
1024     if (is_nestmate && log_is_enabled(Debug, class, nestmates)) {
1025       ModuleEntry* module = ik->module();
1026       const char * module_name = module->is_named() ? module->name()->as_C_string() : UNNAMED_MODULE;
1027       log_debug(class, nestmates)("Dynamic nestmate: %s/%s, nest_host %s, %s",
1028                                   module_name,
1029                                   ik->external_name(),
1030                                   host_class->external_name(),
1031                                   ik->is_hidden() ? "is hidden" : "is not hidden");
1032     }
1033   }
1034 
1035   if ((!is_hidden || is_nestmate) && !Reflection::is_same_class_package(lookup_k, ik)) {
1036     // non-hidden class or nestmate class must be in the same package as the Lookup class
1037     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class and defined class are in different packages");
1038   }
1039 
1040   if (init) {
1041     ik->initialize(CHECK_NULL);
1042   } else {
1043     ik->link_class(CHECK_NULL);
1044   }
1045 
1046   return (jclass) JNIHandles::make_local(THREAD, ik->java_mirror());
1047 }
1048 
1049 JVM_ENTRY_PROF(jclass, JVM_DefineClass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
1050   return jvm_define_class_common(name, loader, buf, len, pd, nullptr, THREAD);
1051 JVM_END
1052 
1053 /*
1054  * Define a class with the specified lookup class.
1055  *  lookup:  Lookup class
1056  *  name:    the name of the class
1057  *  buf:     class bytes
1058  *  len:     length of class bytes
1059  *  pd:      protection domain
1060  *  init:    initialize the class
1061  *  flags:   properties of the class
1062  *  classData: private static pre-initialized field
1063  */
1064 JVM_ENTRY_PROF(jclass, JVM_LookupDefineClass, JVM_LookupDefineClass(JNIEnv *env, jclass lookup, const char *name, const jbyte *buf,
1065           jsize len, jobject pd, jboolean initialize, int flags, jobject classData))
1066 
1067   if (lookup == nullptr) {
1068     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class is null");
1069   }
1070 
1071   assert(buf != nullptr, "buf must not be null");
1072 
1073   return jvm_lookup_define_class(lookup, name, buf, len, pd, initialize, flags, classData, THREAD);
1074 JVM_END
1075 
1076 JVM_ENTRY_PROF(jclass, JVM_DefineClassWithSource, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
1077   return jvm_define_class_common(name, loader, buf, len, pd, source, THREAD);
1078 JVM_END
1079 
1080 JVM_ENTRY_PROF(jclass, JVM_FindLoadedClass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
1081   ResourceMark rm(THREAD);
1082 
1083   Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
1084   char* str = java_lang_String::as_utf8_string(h_name());
1085 
1086   // Sanity check, don't expect null
1087   if (str == nullptr) return nullptr;
1088 
1089   // Internalize the string, converting '.' to '/' in string.
1090   char* p = (char*)str;
1091   while (*p != '\0') {
1092     if (*p == '.') {
1093       *p = '/';
1094     }
1095     p++;
1096   }
1097 
1098   const int str_len = (int)(p - str);
1099   if (str_len > Symbol::max_length()) {
1100     // It's impossible to create this class;  the name cannot fit
1101     // into the constant pool.
1102     return nullptr;
1103   }
1104   TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len);
1105 
1106   // Security Note:
1107   //   The Java level wrapper will perform the necessary security check allowing
1108   //   us to pass the null as the initiating class loader.
1109   Handle h_loader(THREAD, JNIHandles::resolve(loader));
1110   Klass* k = SystemDictionary::find_instance_or_array_klass(THREAD, klass_name, h_loader);
1111 #if INCLUDE_CDS
1112   if (k == nullptr) {
1113     // If the class is not already loaded, try to see if it's in the shared
1114     // archive for the current classloader (h_loader).
1115     k = SystemDictionaryShared::find_or_load_shared_class(klass_name, h_loader, CHECK_NULL);
1116   }
1117 #endif
1118   return (k == nullptr) ? nullptr :
1119             (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
1120 JVM_END
1121 
1122 // Module support //////////////////////////////////////////////////////////////////////////////
1123 
1124 JVM_ENTRY_PROF(void, JVM_DefineModule, JVM_DefineModule(JNIEnv *env, jobject module, jboolean is_open, jstring version,
1125                                                    jstring location, jobjectArray packages))
1126   Handle h_module (THREAD, JNIHandles::resolve(module));
1127   Modules::define_module(h_module, is_open, version, location, packages, CHECK);
1128 JVM_END
1129 
1130 JVM_ENTRY_PROF(void, JVM_SetBootLoaderUnnamedModule, JVM_SetBootLoaderUnnamedModule(JNIEnv *env, jobject module))
1131   Handle h_module (THREAD, JNIHandles::resolve(module));
1132   Modules::set_bootloader_unnamed_module(h_module, CHECK);
1133 JVM_END
1134 
1135 JVM_ENTRY_PROF(void, JVM_AddModuleExports, JVM_AddModuleExports(JNIEnv *env, jobject from_module, jstring package, jobject to_module))
1136   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1137   Handle h_to_module (THREAD, JNIHandles::resolve(to_module));
1138   Modules::add_module_exports_qualified(h_from_module, package, h_to_module, CHECK);
1139 JVM_END
1140 
1141 JVM_ENTRY_PROF(void, JVM_AddModuleExportsToAllUnnamed, JVM_AddModuleExportsToAllUnnamed(JNIEnv *env, jobject from_module, jstring package))
1142   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1143   Modules::add_module_exports_to_all_unnamed(h_from_module, package, CHECK);
1144 JVM_END
1145 
1146 JVM_ENTRY_PROF(void, JVM_AddModuleExportsToAll, JVM_AddModuleExportsToAll(JNIEnv *env, jobject from_module, jstring package))
1147   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1148   Modules::add_module_exports(h_from_module, package, Handle(), CHECK);
1149 JVM_END
1150 
1151 JVM_ENTRY_PROF(void, JVM_AddReadsModule, JVM_AddReadsModule(JNIEnv *env, jobject from_module, jobject source_module))
1152   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1153   Handle h_source_module (THREAD, JNIHandles::resolve(source_module));
1154   Modules::add_reads_module(h_from_module, h_source_module, CHECK);
1155 JVM_END
1156 
1157 JVM_ENTRY_PROF(void, JVM_DefineArchivedModules, JVM_DefineArchivedModules(JNIEnv *env, jobject platform_loader, jobject system_loader))
1158   Handle h_platform_loader (THREAD, JNIHandles::resolve(platform_loader));
1159   Handle h_system_loader (THREAD, JNIHandles::resolve(system_loader));
1160   Modules::define_archived_modules(h_platform_loader, h_system_loader, CHECK);
1161 JVM_END
1162 
1163 // Reflection support //////////////////////////////////////////////////////////////////////////////
1164 
1165 JVM_ENTRY_PROF(jstring, JVM_InitClassName, JVM_InitClassName(JNIEnv *env, jclass cls))
1166   assert (cls != nullptr, "illegal class");
1167   JvmtiVMObjectAllocEventCollector oam;
1168   ResourceMark rm(THREAD);
1169   HandleMark hm(THREAD);
1170   Handle java_class(THREAD, JNIHandles::resolve(cls));
1171   oop result = java_lang_Class::name(java_class, CHECK_NULL);
1172   return (jstring) JNIHandles::make_local(THREAD, result);
1173 JVM_END
1174 
1175 
1176 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassInterfaces, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1177   JvmtiVMObjectAllocEventCollector oam;
1178   oop mirror = JNIHandles::resolve_non_null(cls);
1179 
1180   // Special handling for primitive objects
1181   if (java_lang_Class::is_primitive(mirror)) {
1182     // Primitive objects does not have any interfaces
1183     objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_NULL);
1184     return (jobjectArray) JNIHandles::make_local(THREAD, r);
1185   }
1186 
1187   Klass* klass = java_lang_Class::as_Klass(mirror);
1188   // Figure size of result array
1189   int size;
1190   if (klass->is_instance_klass()) {
1191     size = InstanceKlass::cast(klass)->local_interfaces()->length();
1192   } else {
1193     assert(klass->is_objArray_klass() || klass->is_typeArray_klass(), "Illegal mirror klass");
1194     size = 2;
1195   }
1196 
1197   // Allocate result array
1198   objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(), size, CHECK_NULL);
1199   objArrayHandle result (THREAD, r);
1200   // Fill in result
1201   if (klass->is_instance_klass()) {
1202     // Regular instance klass, fill in all local interfaces
1203     for (int index = 0; index < size; index++) {
1204       Klass* k = InstanceKlass::cast(klass)->local_interfaces()->at(index);
1205       result->obj_at_put(index, k->java_mirror());
1206     }
1207   } else {
1208     // All arrays implement java.lang.Cloneable and java.io.Serializable
1209     result->obj_at_put(0, vmClasses::Cloneable_klass()->java_mirror());
1210     result->obj_at_put(1, vmClasses::Serializable_klass()->java_mirror());
1211   }
1212   return (jobjectArray) JNIHandles::make_local(THREAD, result());
1213 JVM_END
1214 
1215 
1216 JVM_ENTRY_PROF(jboolean, JVM_IsInterface, JVM_IsInterface(JNIEnv *env, jclass cls))
1217   oop mirror = JNIHandles::resolve_non_null(cls);
1218   if (java_lang_Class::is_primitive(mirror)) {
1219     return JNI_FALSE;
1220   }
1221   Klass* k = java_lang_Class::as_Klass(mirror);
1222   jboolean result = k->is_interface();
1223   assert(!result || k->is_instance_klass(),
1224          "all interfaces are instance types");
1225   // The compiler intrinsic for isInterface tests the
1226   // Klass::_access_flags bits in the same way.
1227   return result;
1228 JVM_END
1229 
1230 JVM_ENTRY_PROF(jboolean, JVM_IsHiddenClass, JVM_IsHiddenClass(JNIEnv *env, jclass cls))
1231   oop mirror = JNIHandles::resolve_non_null(cls);
1232   if (java_lang_Class::is_primitive(mirror)) {
1233     return JNI_FALSE;
1234   }
1235   Klass* k = java_lang_Class::as_Klass(mirror);
1236   return k->is_hidden();
1237 JVM_END
1238 
1239 JVM_ENTRY_PROF(jobject, JVM_GetProtectionDomain, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1240   oop mirror = JNIHandles::resolve_non_null(cls);
1241   if (mirror == nullptr) {
1242     THROW_(vmSymbols::java_lang_NullPointerException(), nullptr);
1243   }
1244 
1245   if (java_lang_Class::is_primitive(mirror)) {
1246     // Primitive types does not have a protection domain.
1247     return nullptr;
1248   }
1249 
1250   oop pd = java_lang_Class::protection_domain(mirror);
1251   return (jobject) JNIHandles::make_local(THREAD, pd);
1252 JVM_END
1253 
1254 class ScopedValueBindingsResolver {
1255 public:
1256   InstanceKlass* Carrier_klass;
1257   ScopedValueBindingsResolver(JavaThread* THREAD) {
1258     Klass *k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ScopedValue_Carrier(), true, THREAD);
1259     Carrier_klass = InstanceKlass::cast(k);
1260   }
1261 };
1262 
1263 JVM_ENTRY_PROF(jobject, JVM_FindScopedValueBindings, JVM_FindScopedValueBindings(JNIEnv *env, jclass cls))
1264   ResourceMark rm(THREAD);
1265   GrowableArray<Handle>* local_array = new GrowableArray<Handle>(12);
1266   JvmtiVMObjectAllocEventCollector oam;
1267 
1268   static ScopedValueBindingsResolver resolver(THREAD);
1269 
1270   // Iterate through Java frames
1271   vframeStream vfst(thread);
1272   for(; !vfst.at_end(); vfst.next()) {
1273     int loc = -1;
1274     // get method of frame
1275     Method* method = vfst.method();
1276 
1277     Symbol *name = method->name();
1278 
1279     InstanceKlass* holder = method->method_holder();
1280     if (name == vmSymbols::runWith_method_name()) {
1281       if (holder == vmClasses::Thread_klass()
1282           || holder == resolver.Carrier_klass) {
1283         loc = 1;
1284       }
1285     }
1286 
1287     if (loc != -1) {
1288       javaVFrame *frame = vfst.asJavaVFrame();
1289       StackValueCollection* locals = frame->locals();
1290       StackValue* head_sv = locals->at(loc); // java/lang/ScopedValue$Snapshot
1291       Handle result = head_sv->get_obj();
1292       assert(!head_sv->obj_is_scalar_replaced(), "found scalar-replaced object");
1293       if (result() != nullptr) {
1294         return JNIHandles::make_local(THREAD, result());
1295       }
1296     }
1297   }
1298 
1299   return nullptr;
1300 JVM_END
1301 
1302 JVM_ENTRY_PROF(jboolean, JVM_IsArrayClass, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1303   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1304   return (k != nullptr) && k->is_array_klass() ? true : false;
1305 JVM_END
1306 
1307 
1308 JVM_ENTRY_PROF(jboolean, JVM_IsPrimitiveClass, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1309   oop mirror = JNIHandles::resolve_non_null(cls);
1310   return (jboolean) java_lang_Class::is_primitive(mirror);
1311 JVM_END
1312 
1313 
1314 JVM_ENTRY_PROF(jint, JVM_GetClassModifiers, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1315   oop mirror = JNIHandles::resolve_non_null(cls);
1316   if (java_lang_Class::is_primitive(mirror)) {
1317     // Primitive type
1318     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1319   }
1320 
1321   Klass* k = java_lang_Class::as_Klass(mirror);
1322   debug_only(u2 computed_modifiers = k->compute_modifier_flags());
1323   assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1324   return k->modifier_flags();
1325 JVM_END
1326 
1327 
1328 // Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1329 
1330 JVM_ENTRY_PROF(jobjectArray, JVM_GetDeclaredClasses, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1331   JvmtiVMObjectAllocEventCollector oam;
1332   // ofClass is a reference to a java_lang_Class object. The mirror object
1333   // of an InstanceKlass
1334   oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1335   if (java_lang_Class::is_primitive(ofMirror) ||
1336       ! java_lang_Class::as_Klass(ofMirror)->is_instance_klass()) {
1337     oop result = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_NULL);
1338     return (jobjectArray)JNIHandles::make_local(THREAD, result);
1339   }
1340 
1341   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(ofMirror));
1342   InnerClassesIterator iter(k);
1343 
1344   if (iter.length() == 0) {
1345     // Neither an inner nor outer class
1346     oop result = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_NULL);
1347     return (jobjectArray)JNIHandles::make_local(THREAD, result);
1348   }
1349 
1350   // find inner class info
1351   constantPoolHandle cp(thread, k->constants());
1352   int length = iter.length();
1353 
1354   // Allocate temp. result array
1355   objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(), length/4, CHECK_NULL);
1356   objArrayHandle result (THREAD, r);
1357   int members = 0;
1358 
1359   for (; !iter.done(); iter.next()) {
1360     int ioff = iter.inner_class_info_index();
1361     int ooff = iter.outer_class_info_index();
1362 
1363     if (ioff != 0 && ooff != 0) {
1364       // Check to see if the name matches the class we're looking for
1365       // before attempting to find the class.
1366       if (cp->klass_name_at_matches(k, ooff)) {
1367         Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1368         if (outer_klass == k) {
1369            Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1370            InstanceKlass* inner_klass = InstanceKlass::cast(ik);
1371 
1372            // Throws an exception if outer klass has not declared k as
1373            // an inner klass
1374            Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1375 
1376            result->obj_at_put(members, inner_klass->java_mirror());
1377            members++;
1378         }
1379       }
1380     }
1381   }
1382 
1383   if (members != length) {
1384     // Return array of right length
1385     objArrayOop res = oopFactory::new_objArray(vmClasses::Class_klass(), members, CHECK_NULL);
1386     for(int i = 0; i < members; i++) {
1387       res->obj_at_put(i, result->obj_at(i));
1388     }
1389     return (jobjectArray)JNIHandles::make_local(THREAD, res);
1390   }
1391 
1392   return (jobjectArray)JNIHandles::make_local(THREAD, result());
1393 JVM_END
1394 
1395 
1396 JVM_ENTRY_PROF(jclass, JVM_GetDeclaringClass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1397 {
1398   // ofClass is a reference to a java_lang_Class object.
1399   oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1400   if (java_lang_Class::is_primitive(ofMirror)) {
1401     return nullptr;
1402   }
1403   Klass* klass = java_lang_Class::as_Klass(ofMirror);
1404   if (!klass->is_instance_klass()) {
1405     return nullptr;
1406   }
1407 
1408   bool inner_is_member = false;
1409   Klass* outer_klass
1410     = InstanceKlass::cast(klass)->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1411   if (outer_klass == nullptr)  return nullptr;  // already a top-level class
1412   if (!inner_is_member)  return nullptr;     // a hidden class (inside a method)
1413   return (jclass) JNIHandles::make_local(THREAD, outer_klass->java_mirror());
1414 }
1415 JVM_END
1416 
1417 JVM_ENTRY_PROF(jstring, JVM_GetSimpleBinaryName, JVM_GetSimpleBinaryName(JNIEnv *env, jclass cls))
1418 {
1419   oop mirror = JNIHandles::resolve_non_null(cls);
1420   if (java_lang_Class::is_primitive(mirror)) {
1421     return nullptr;
1422   }
1423   Klass* klass = java_lang_Class::as_Klass(mirror);
1424   if (!klass->is_instance_klass()) {
1425     return nullptr;
1426   }
1427   InstanceKlass* k = InstanceKlass::cast(klass);
1428   int ooff = 0, noff = 0;
1429   if (k->find_inner_classes_attr(&ooff, &noff, THREAD)) {
1430     if (noff != 0) {
1431       constantPoolHandle i_cp(thread, k->constants());
1432       Symbol* name = i_cp->symbol_at(noff);
1433       Handle str = java_lang_String::create_from_symbol(name, CHECK_NULL);
1434       return (jstring) JNIHandles::make_local(THREAD, str());
1435     }
1436   }
1437   return nullptr;
1438 }
1439 JVM_END
1440 
1441 JVM_ENTRY_PROF(jstring, JVM_GetClassSignature, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1442   assert (cls != nullptr, "illegal class");
1443   JvmtiVMObjectAllocEventCollector oam;
1444   ResourceMark rm(THREAD);
1445   oop mirror = JNIHandles::resolve_non_null(cls);
1446   // Return null for arrays and primitives
1447   if (!java_lang_Class::is_primitive(mirror)) {
1448     Klass* k = java_lang_Class::as_Klass(mirror);
1449     if (k->is_instance_klass()) {
1450       Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1451       if (sym == nullptr) return nullptr;
1452       Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1453       return (jstring) JNIHandles::make_local(THREAD, str());
1454     }
1455   }
1456   return nullptr;
1457 JVM_END
1458 
1459 
1460 JVM_ENTRY_PROF(jbyteArray, JVM_GetClassAnnotations, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1461   assert (cls != nullptr, "illegal class");
1462   oop mirror = JNIHandles::resolve_non_null(cls);
1463   // Return null for arrays and primitives
1464   if (!java_lang_Class::is_primitive(mirror)) {
1465     Klass* k = java_lang_Class::as_Klass(mirror);
1466     if (k->is_instance_klass()) {
1467       typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1468       return (jbyteArray) JNIHandles::make_local(THREAD, a);
1469     }
1470   }
1471   return nullptr;
1472 JVM_END
1473 
1474 
1475 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd) {
1476   // some of this code was adapted from from jni_FromReflectedField
1477 
1478   oop reflected = JNIHandles::resolve_non_null(field);
1479   oop mirror    = java_lang_reflect_Field::clazz(reflected);
1480   Klass* k    = java_lang_Class::as_Klass(mirror);
1481   int slot      = java_lang_reflect_Field::slot(reflected);
1482   int modifiers = java_lang_reflect_Field::modifiers(reflected);
1483 
1484   InstanceKlass* ik = InstanceKlass::cast(k);
1485   int offset = ik->field_offset(slot);
1486 
1487   if (modifiers & JVM_ACC_STATIC) {
1488     // for static fields we only look in the current class
1489     if (!ik->find_local_field_from_offset(offset, true, &fd)) {
1490       assert(false, "cannot find static field");
1491       return false;
1492     }
1493   } else {
1494     // for instance fields we start with the current class and work
1495     // our way up through the superclass chain
1496     if (!ik->find_field_from_offset(offset, false, &fd)) {
1497       assert(false, "cannot find instance field");
1498       return false;
1499     }
1500   }
1501   return true;
1502 }
1503 
1504 static Method* jvm_get_method_common(jobject method) {
1505   // some of this code was adapted from from jni_FromReflectedMethod
1506 
1507   oop reflected = JNIHandles::resolve_non_null(method);
1508   oop mirror    = nullptr;
1509   int slot      = 0;
1510 
1511   if (reflected->klass() == vmClasses::reflect_Constructor_klass()) {
1512     mirror = java_lang_reflect_Constructor::clazz(reflected);
1513     slot   = java_lang_reflect_Constructor::slot(reflected);
1514   } else {
1515     assert(reflected->klass() == vmClasses::reflect_Method_klass(),
1516            "wrong type");
1517     mirror = java_lang_reflect_Method::clazz(reflected);
1518     slot   = java_lang_reflect_Method::slot(reflected);
1519   }
1520   Klass* k = java_lang_Class::as_Klass(mirror);
1521 
1522   Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
1523   assert(m != nullptr, "cannot find method");
1524   return m;  // caller has to deal with null in product mode
1525 }
1526 
1527 /* Type use annotations support (JDK 1.8) */
1528 
1529 JVM_ENTRY_PROF(jbyteArray, JVM_GetClassTypeAnnotations, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1530   assert (cls != nullptr, "illegal class");
1531   ResourceMark rm(THREAD);
1532   // Return null for arrays and primitives
1533   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1534     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1535     if (k->is_instance_klass()) {
1536       AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1537       if (type_annotations != nullptr) {
1538         typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1539         return (jbyteArray) JNIHandles::make_local(THREAD, a);
1540       }
1541     }
1542   }
1543   return nullptr;
1544 JVM_END
1545 
1546 JVM_ENTRY_PROF(jbyteArray, JVM_GetMethodTypeAnnotations, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1547   assert (method != nullptr, "illegal method");
1548   // method is a handle to a java.lang.reflect.Method object
1549   Method* m = jvm_get_method_common(method);
1550   if (m == nullptr) {
1551     return nullptr;
1552   }
1553 
1554   AnnotationArray* type_annotations = m->type_annotations();
1555   if (type_annotations != nullptr) {
1556     typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1557     return (jbyteArray) JNIHandles::make_local(THREAD, a);
1558   }
1559 
1560   return nullptr;
1561 JVM_END
1562 
1563 JVM_ENTRY_PROF(jbyteArray, JVM_GetFieldTypeAnnotations, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1564   assert (field != nullptr, "illegal field");
1565   fieldDescriptor fd;
1566   bool gotFd = jvm_get_field_common(field, fd);
1567   if (!gotFd) {
1568     return nullptr;
1569   }
1570 
1571   return (jbyteArray) JNIHandles::make_local(THREAD, Annotations::make_java_array(fd.type_annotations(), THREAD));
1572 JVM_END
1573 
1574 static void bounds_check(const constantPoolHandle& cp, jint index, TRAPS) {
1575   if (!cp->is_within_bounds(index)) {
1576     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1577   }
1578 }
1579 
1580 JVM_ENTRY_PROF(jobjectArray, JVM_GetMethodParameters, JVM_GetMethodParameters(JNIEnv *env, jobject method))
1581 {
1582   // method is a handle to a java.lang.reflect.Method object
1583   Method* method_ptr = jvm_get_method_common(method);
1584   methodHandle mh (THREAD, method_ptr);
1585   Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
1586   const int num_params = mh->method_parameters_length();
1587 
1588   if (num_params < 0) {
1589     // A -1 return value from method_parameters_length means there is no
1590     // parameter data.  Return null to indicate this to the reflection
1591     // API.
1592     assert(num_params == -1, "num_params should be -1 if it is less than zero");
1593     return (jobjectArray)nullptr;
1594   } else {
1595     // Otherwise, we return something up to reflection, even if it is
1596     // a zero-length array.  Why?  Because in some cases this can
1597     // trigger a MalformedParametersException.
1598 
1599     // make sure all the symbols are properly formatted
1600     for (int i = 0; i < num_params; i++) {
1601       MethodParametersElement* params = mh->method_parameters_start();
1602       int index = params[i].name_cp_index;
1603       constantPoolHandle cp(THREAD, mh->constants());
1604       bounds_check(cp, index, CHECK_NULL);
1605 
1606       if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
1607         THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
1608                        "Wrong type at constant pool index");
1609       }
1610 
1611     }
1612 
1613     objArrayOop result_oop = oopFactory::new_objArray(vmClasses::reflect_Parameter_klass(), num_params, CHECK_NULL);
1614     objArrayHandle result (THREAD, result_oop);
1615 
1616     for (int i = 0; i < num_params; i++) {
1617       MethodParametersElement* params = mh->method_parameters_start();
1618       // For a 0 index, give a null symbol
1619       Symbol* sym = 0 != params[i].name_cp_index ?
1620         mh->constants()->symbol_at(params[i].name_cp_index) : nullptr;
1621       int flags = params[i].flags;
1622       oop param = Reflection::new_parameter(reflected_method, i, sym,
1623                                             flags, CHECK_NULL);
1624       result->obj_at_put(i, param);
1625     }
1626     return (jobjectArray)JNIHandles::make_local(THREAD, result());
1627   }
1628 }
1629 JVM_END
1630 
1631 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1632 
1633 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassDeclaredFields, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1634 {
1635   JvmtiVMObjectAllocEventCollector oam;
1636 
1637   oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1638   // Exclude primitive types and array types
1639   if (java_lang_Class::is_primitive(ofMirror) ||
1640       java_lang_Class::as_Klass(ofMirror)->is_array_klass()) {
1641     // Return empty array
1642     oop res = oopFactory::new_objArray(vmClasses::reflect_Field_klass(), 0, CHECK_NULL);
1643     return (jobjectArray) JNIHandles::make_local(THREAD, res);
1644   }
1645 
1646   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(ofMirror));
1647   constantPoolHandle cp(THREAD, k->constants());
1648 
1649   // Ensure class is linked
1650   k->link_class(CHECK_NULL);
1651 
1652   // Allocate result
1653   int num_fields;
1654 
1655   if (publicOnly) {
1656     num_fields = 0;
1657     for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1658       if (fs.access_flags().is_public()) ++num_fields;
1659     }
1660   } else {
1661     num_fields = k->java_fields_count();
1662   }
1663 
1664   objArrayOop r = oopFactory::new_objArray(vmClasses::reflect_Field_klass(), num_fields, CHECK_NULL);
1665   objArrayHandle result (THREAD, r);
1666 
1667   int out_idx = 0;
1668   fieldDescriptor fd;
1669   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1670     if (!publicOnly || fs.access_flags().is_public()) {
1671       fd.reinitialize(k, fs.index());
1672       oop field = Reflection::new_field(&fd, CHECK_NULL);
1673       result->obj_at_put(out_idx, field);
1674       ++out_idx;
1675     }
1676   }
1677   assert(out_idx == num_fields, "just checking");
1678   return (jobjectArray) JNIHandles::make_local(THREAD, result());
1679 }
1680 JVM_END
1681 
1682 // A class is a record if and only if it is final and a direct subclass of
1683 // java.lang.Record and has a Record attribute; otherwise, it is not a record.
1684 JVM_ENTRY_PROF(jboolean, JVM_IsRecord, JVM_IsRecord(JNIEnv *env, jclass cls))
1685 {
1686   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1687   if (k != nullptr && k->is_instance_klass()) {
1688     InstanceKlass* ik = InstanceKlass::cast(k);
1689     return ik->is_record();
1690   } else {
1691     return false;
1692   }
1693 }
1694 JVM_END
1695 
1696 // Returns an array containing the components of the Record attribute,
1697 // or null if the attribute is not present.
1698 //
1699 // Note that this function returns the components of the Record attribute
1700 // even if the class is not a record.
1701 JVM_ENTRY_PROF(jobjectArray, JVM_GetRecordComponents, JVM_GetRecordComponents(JNIEnv* env, jclass ofClass))
1702 {
1703   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass));
1704   assert(c->is_instance_klass(), "must be");
1705   InstanceKlass* ik = InstanceKlass::cast(c);
1706 
1707   Array<RecordComponent*>* components = ik->record_components();
1708   if (components != nullptr) {
1709     JvmtiVMObjectAllocEventCollector oam;
1710     constantPoolHandle cp(THREAD, ik->constants());
1711     int length = components->length();
1712     assert(length >= 0, "unexpected record_components length");
1713     objArrayOop record_components =
1714       oopFactory::new_objArray(vmClasses::RecordComponent_klass(), length, CHECK_NULL);
1715     objArrayHandle components_h (THREAD, record_components);
1716 
1717     for (int x = 0; x < length; x++) {
1718       RecordComponent* component = components->at(x);
1719       assert(component != nullptr, "unexpected null record component");
1720       oop component_oop = java_lang_reflect_RecordComponent::create(ik, component, CHECK_NULL);
1721       components_h->obj_at_put(x, component_oop);
1722     }
1723     return (jobjectArray)JNIHandles::make_local(THREAD, components_h());
1724   }
1725 
1726   return nullptr;
1727 }
1728 JVM_END
1729 
1730 static jobjectArray get_class_declared_methods_helper(
1731                                   JNIEnv *env,
1732                                   jclass ofClass, jboolean publicOnly,
1733                                   bool want_constructor,
1734                                   Klass* klass, TRAPS) {
1735 
1736   JvmtiVMObjectAllocEventCollector oam;
1737 
1738   oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1739   // Exclude primitive types and array types
1740   if (java_lang_Class::is_primitive(ofMirror)
1741       || java_lang_Class::as_Klass(ofMirror)->is_array_klass()) {
1742     // Return empty array
1743     oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
1744     return (jobjectArray) JNIHandles::make_local(THREAD, res);
1745   }
1746 
1747   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(ofMirror));
1748 
1749   // Ensure class is linked
1750   k->link_class(CHECK_NULL);
1751 
1752   Array<Method*>* methods = k->methods();
1753   int methods_length = methods->length();
1754 
1755   // Save original method_idnum in case of redefinition, which can change
1756   // the idnum of obsolete methods.  The new method will have the same idnum
1757   // but if we refresh the methods array, the counts will be wrong.
1758   ResourceMark rm(THREAD);
1759   GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
1760   int num_methods = 0;
1761 
1762   // Select methods matching the criteria.
1763   for (int i = 0; i < methods_length; i++) {
1764     Method* method = methods->at(i);
1765     if (want_constructor && !method->is_object_initializer()) {
1766       continue;
1767     }
1768     if (!want_constructor &&
1769         (method->is_object_initializer() || method->is_static_initializer() ||
1770          method->is_overpass())) {
1771       continue;
1772     }
1773     if (publicOnly && !method->is_public()) {
1774       continue;
1775     }
1776     idnums->push(method->method_idnum());
1777     ++num_methods;
1778   }
1779 
1780   // Allocate result
1781   objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
1782   objArrayHandle result (THREAD, r);
1783 
1784   // Now just put the methods that we selected above, but go by their idnum
1785   // in case of redefinition.  The methods can be redefined at any safepoint,
1786   // so above when allocating the oop array and below when creating reflect
1787   // objects.
1788   for (int i = 0; i < num_methods; i++) {
1789     methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
1790     if (method.is_null()) {
1791       // Method may have been deleted and seems this API can handle null
1792       // Otherwise should probably put a method that throws NSME
1793       result->obj_at_put(i, nullptr);
1794     } else {
1795       oop m;
1796       if (want_constructor) {
1797         m = Reflection::new_constructor(method, CHECK_NULL);
1798       } else {
1799         m = Reflection::new_method(method, false, CHECK_NULL);
1800       }
1801       result->obj_at_put(i, m);
1802     }
1803   }
1804 
1805   return (jobjectArray) JNIHandles::make_local(THREAD, result());
1806 }
1807 
1808 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassDeclaredMethods, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1809 {
1810   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1811                                            /*want_constructor*/ false,
1812                                            vmClasses::reflect_Method_klass(), THREAD);
1813 }
1814 JVM_END
1815 
1816 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassDeclaredConstructors, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1817 {
1818   return get_class_declared_methods_helper(env, ofClass, publicOnly,
1819                                            /*want_constructor*/ true,
1820                                            vmClasses::reflect_Constructor_klass(), THREAD);
1821 }
1822 JVM_END
1823 
1824 JVM_ENTRY_PROF(jint, JVM_GetClassAccessFlags, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
1825 {
1826   oop mirror = JNIHandles::resolve_non_null(cls);
1827   if (java_lang_Class::is_primitive(mirror)) {
1828     // Primitive type
1829     return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1830   }
1831 
1832   Klass* k = java_lang_Class::as_Klass(mirror);
1833   return k->access_flags().as_class_flags();
1834 }
1835 JVM_END
1836 
1837 JVM_ENTRY_PROF(jboolean, JVM_AreNestMates, JVM_AreNestMates(JNIEnv *env, jclass current, jclass member))
1838 {
1839   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1840   assert(c->is_instance_klass(), "must be");
1841   InstanceKlass* ck = InstanceKlass::cast(c);
1842   Klass* m = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(member));
1843   assert(m->is_instance_klass(), "must be");
1844   InstanceKlass* mk = InstanceKlass::cast(m);
1845   return ck->has_nestmate_access_to(mk, THREAD);
1846 }
1847 JVM_END
1848 
1849 JVM_ENTRY_PROF(jclass, JVM_GetNestHost, JVM_GetNestHost(JNIEnv* env, jclass current))
1850 {
1851   // current is not a primitive or array class
1852   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1853   assert(c->is_instance_klass(), "must be");
1854   InstanceKlass* ck = InstanceKlass::cast(c);
1855   InstanceKlass* host = ck->nest_host(THREAD);
1856   return (jclass) (host == nullptr ? nullptr :
1857                    JNIHandles::make_local(THREAD, host->java_mirror()));
1858 }
1859 JVM_END
1860 
1861 JVM_ENTRY_PROF(jobjectArray, JVM_GetNestMembers, JVM_GetNestMembers(JNIEnv* env, jclass current))
1862 {
1863   // current is not a primitive or array class
1864   ResourceMark rm(THREAD);
1865   Klass* c = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(current));
1866   assert(c->is_instance_klass(), "must be");
1867   InstanceKlass* ck = InstanceKlass::cast(c);
1868   InstanceKlass* host = ck->nest_host(THREAD);
1869 
1870   log_trace(class, nestmates)("Calling GetNestMembers for type %s with nest-host %s",
1871                               ck->external_name(), host->external_name());
1872   {
1873     JvmtiVMObjectAllocEventCollector oam;
1874     Array<u2>* members = host->nest_members();
1875     int length = members == nullptr ? 0 : members->length();
1876 
1877     log_trace(class, nestmates)(" - host has %d listed nest members", length);
1878 
1879     // nest host is first in the array so make it one bigger
1880     objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(),
1881                                              length + 1, CHECK_NULL);
1882     objArrayHandle result(THREAD, r);
1883     result->obj_at_put(0, host->java_mirror());
1884     if (length != 0) {
1885       int count = 0;
1886       for (int i = 0; i < length; i++) {
1887         int cp_index = members->at(i);
1888         Klass* k = host->constants()->klass_at(cp_index, THREAD);
1889         if (HAS_PENDING_EXCEPTION) {
1890           if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
1891             return nullptr; // propagate VMEs
1892           }
1893           if (log_is_enabled(Trace, class, nestmates)) {
1894             stringStream ss;
1895             char* target_member_class = host->constants()->klass_name_at(cp_index)->as_C_string();
1896             ss.print(" - resolution of nest member %s failed: ", target_member_class);
1897             java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
1898             log_trace(class, nestmates)("%s", ss.as_string());
1899           }
1900           CLEAR_PENDING_EXCEPTION;
1901           continue;
1902         }
1903         if (k->is_instance_klass()) {
1904           InstanceKlass* ik = InstanceKlass::cast(k);
1905           InstanceKlass* nest_host_k = ik->nest_host(CHECK_NULL);
1906           if (nest_host_k == host) {
1907             result->obj_at_put(count+1, k->java_mirror());
1908             count++;
1909             log_trace(class, nestmates)(" - [%d] = %s", count, ik->external_name());
1910           } else {
1911             log_trace(class, nestmates)(" - skipping member %s with different host %s",
1912                                         ik->external_name(), nest_host_k->external_name());
1913           }
1914         } else {
1915           log_trace(class, nestmates)(" - skipping member %s that is not an instance class",
1916                                       k->external_name());
1917         }
1918       }
1919       if (count < length) {
1920         // we had invalid entries so we need to compact the array
1921         log_trace(class, nestmates)(" - compacting array from length %d to %d",
1922                                     length + 1, count + 1);
1923 
1924         objArrayOop r2 = oopFactory::new_objArray(vmClasses::Class_klass(),
1925                                                   count + 1, CHECK_NULL);
1926         objArrayHandle result2(THREAD, r2);
1927         for (int i = 0; i < count + 1; i++) {
1928           result2->obj_at_put(i, result->obj_at(i));
1929         }
1930         return (jobjectArray)JNIHandles::make_local(THREAD, result2());
1931       }
1932     }
1933     else {
1934       assert(host == ck || ck->is_hidden(), "must be singleton nest or dynamic nestmate");
1935     }
1936     return (jobjectArray)JNIHandles::make_local(THREAD, result());
1937   }
1938 }
1939 JVM_END
1940 
1941 JVM_ENTRY_PROF(jobjectArray, JVM_GetPermittedSubclasses, JVM_GetPermittedSubclasses(JNIEnv* env, jclass current))
1942 {
1943   oop mirror = JNIHandles::resolve_non_null(current);
1944   assert(!java_lang_Class::is_primitive(mirror), "should not be");
1945   Klass* c = java_lang_Class::as_Klass(mirror);
1946   assert(c->is_instance_klass(), "must be");
1947   InstanceKlass* ik = InstanceKlass::cast(c);
1948   ResourceMark rm(THREAD);
1949   log_trace(class, sealed)("Calling GetPermittedSubclasses for %s type %s",
1950                            ik->is_sealed() ? "sealed" : "non-sealed", ik->external_name());
1951   if (ik->is_sealed()) {
1952     JvmtiVMObjectAllocEventCollector oam;
1953     Array<u2>* subclasses = ik->permitted_subclasses();
1954     int length = subclasses->length();
1955 
1956     log_trace(class, sealed)(" - sealed class has %d permitted subclasses", length);
1957 
1958     objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(),
1959                                              length, CHECK_NULL);
1960     objArrayHandle result(THREAD, r);
1961     int count = 0;
1962     for (int i = 0; i < length; i++) {
1963       int cp_index = subclasses->at(i);
1964       Klass* k = ik->constants()->klass_at(cp_index, THREAD);
1965       if (HAS_PENDING_EXCEPTION) {
1966         if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
1967           return nullptr; // propagate VMEs
1968         }
1969         if (log_is_enabled(Trace, class, sealed)) {
1970           stringStream ss;
1971           char* permitted_subclass = ik->constants()->klass_name_at(cp_index)->as_C_string();
1972           ss.print(" - resolution of permitted subclass %s failed: ", permitted_subclass);
1973           java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
1974           log_trace(class, sealed)("%s", ss.as_string());
1975         }
1976 
1977         CLEAR_PENDING_EXCEPTION;
1978         continue;
1979       }
1980       if (k->is_instance_klass()) {
1981         result->obj_at_put(count++, k->java_mirror());
1982         log_trace(class, sealed)(" - [%d] = %s", count, k->external_name());
1983       }
1984     }
1985     if (count < length) {
1986       // we had invalid entries so we need to compact the array
1987       objArrayOop r2 = oopFactory::new_objArray(vmClasses::Class_klass(),
1988                                                 count, CHECK_NULL);
1989       objArrayHandle result2(THREAD, r2);
1990       for (int i = 0; i < count; i++) {
1991         result2->obj_at_put(i, result->obj_at(i));
1992       }
1993       return (jobjectArray)JNIHandles::make_local(THREAD, result2());
1994     }
1995     return (jobjectArray)JNIHandles::make_local(THREAD, result());
1996   } else {
1997     return nullptr;
1998   }
1999 }
2000 JVM_END
2001 
2002 // Constant pool access //////////////////////////////////////////////////////////
2003 
2004 JVM_ENTRY_PROF(jobject, JVM_GetClassConstantPool, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
2005 {
2006   JvmtiVMObjectAllocEventCollector oam;
2007   oop mirror = JNIHandles::resolve_non_null(cls);
2008   // Return null for primitives and arrays
2009   if (!java_lang_Class::is_primitive(mirror)) {
2010     Klass* k = java_lang_Class::as_Klass(mirror);
2011     if (k->is_instance_klass()) {
2012       InstanceKlass* k_h = InstanceKlass::cast(k);
2013       Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
2014       reflect_ConstantPool::set_cp(jcp(), k_h->constants());
2015       return JNIHandles::make_local(THREAD, jcp());
2016     }
2017   }
2018   return nullptr;
2019 }
2020 JVM_END
2021 
2022 
2023 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetSize, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
2024 {
2025   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2026   return cp->length();
2027 }
2028 JVM_END
2029 
2030 
2031 JVM_ENTRY_PROF(jclass, JVM_ConstantPoolGetClassAt, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2032 {
2033   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2034   bounds_check(cp, index, CHECK_NULL);
2035   constantTag tag = cp->tag_at(index);
2036   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2037     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2038   }
2039   Klass* k = cp->klass_at(index, CHECK_NULL);
2040   return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
2041 }
2042 JVM_END
2043 
2044 JVM_ENTRY_PROF(jclass, JVM_ConstantPoolGetClassAtIfLoaded, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2045 {
2046   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2047   bounds_check(cp, index, CHECK_NULL);
2048   constantTag tag = cp->tag_at(index);
2049   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2050     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2051   }
2052   Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
2053   if (k == nullptr) return nullptr;
2054   return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
2055 }
2056 JVM_END
2057 
2058 static jobject get_method_at_helper(const constantPoolHandle& cp, jint index, bool force_resolution, TRAPS) {
2059   constantTag tag = cp->tag_at(index);
2060   if (!tag.is_method() && !tag.is_interface_method()) {
2061     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2062   }
2063   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2064   Klass* k_o;
2065   if (force_resolution) {
2066     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2067   } else {
2068     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2069     if (k_o == nullptr) return nullptr;
2070   }
2071   InstanceKlass* k = InstanceKlass::cast(k_o);
2072   Symbol* name = cp->uncached_name_ref_at(index);
2073   Symbol* sig  = cp->uncached_signature_ref_at(index);
2074   methodHandle m (THREAD, k->find_method(name, sig));
2075   if (m.is_null()) {
2076     THROW_MSG_NULL(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2077   }
2078   oop method;
2079   if (m->is_object_initializer()) {
2080     method = Reflection::new_constructor(m, CHECK_NULL);
2081   } else {
2082     // new_method accepts <clinit> as Method here
2083     method = Reflection::new_method(m, true, CHECK_NULL);
2084   }
2085   return JNIHandles::make_local(THREAD, method);
2086 }
2087 
2088 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetMethodAt, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2089 {
2090   JvmtiVMObjectAllocEventCollector oam;
2091   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2092   bounds_check(cp, index, CHECK_NULL);
2093   jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2094   return res;
2095 }
2096 JVM_END
2097 
2098 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetMethodAtIfLoaded, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2099 {
2100   JvmtiVMObjectAllocEventCollector oam;
2101   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2102   bounds_check(cp, index, CHECK_NULL);
2103   jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2104   return res;
2105 }
2106 JVM_END
2107 
2108 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2109   constantTag tag = cp->tag_at(index);
2110   if (!tag.is_field()) {
2111     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2112   }
2113   int klass_ref  = cp->uncached_klass_ref_index_at(index);
2114   Klass* k_o;
2115   if (force_resolution) {
2116     k_o = cp->klass_at(klass_ref, CHECK_NULL);
2117   } else {
2118     k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2119     if (k_o == nullptr) return nullptr;
2120   }
2121   InstanceKlass* k = InstanceKlass::cast(k_o);
2122   Symbol* name = cp->uncached_name_ref_at(index);
2123   Symbol* sig  = cp->uncached_signature_ref_at(index);
2124   fieldDescriptor fd;
2125   Klass* target_klass = k->find_field(name, sig, &fd);
2126   if (target_klass == nullptr) {
2127     THROW_MSG_NULL(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2128   }
2129   oop field = Reflection::new_field(&fd, CHECK_NULL);
2130   return JNIHandles::make_local(THREAD, field);
2131 }
2132 
2133 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetFieldAt, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2134 {
2135   JvmtiVMObjectAllocEventCollector oam;
2136   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2137   bounds_check(cp, index, CHECK_NULL);
2138   jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2139   return res;
2140 }
2141 JVM_END
2142 
2143 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetFieldAtIfLoaded, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2144 {
2145   JvmtiVMObjectAllocEventCollector oam;
2146   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2147   bounds_check(cp, index, CHECK_NULL);
2148   jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2149   return res;
2150 }
2151 JVM_END
2152 
2153 JVM_ENTRY_PROF(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2154 {
2155   JvmtiVMObjectAllocEventCollector oam;
2156   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2157   bounds_check(cp, index, CHECK_NULL);
2158   constantTag tag = cp->tag_at(index);
2159   if (!tag.is_field_or_method()) {
2160     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2161   }
2162   int klass_ref = cp->uncached_klass_ref_index_at(index);
2163   Symbol*  klass_name  = cp->klass_name_at(klass_ref);
2164   Symbol*  member_name = cp->uncached_name_ref_at(index);
2165   Symbol*  member_sig  = cp->uncached_signature_ref_at(index);
2166   objArrayOop  dest_o = oopFactory::new_objArray(vmClasses::String_klass(), 3, CHECK_NULL);
2167   objArrayHandle dest(THREAD, dest_o);
2168   Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2169   dest->obj_at_put(0, str());
2170   str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2171   dest->obj_at_put(1, str());
2172   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2173   dest->obj_at_put(2, str());
2174   return (jobjectArray) JNIHandles::make_local(THREAD, dest());
2175 }
2176 JVM_END
2177 
2178 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetClassRefIndexAt, JVM_ConstantPoolGetClassRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2179 {
2180   JvmtiVMObjectAllocEventCollector oam;
2181   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2182   bounds_check(cp, index, CHECK_0);
2183   constantTag tag = cp->tag_at(index);
2184   if (!tag.is_field_or_method()) {
2185     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2186   }
2187   return (jint) cp->uncached_klass_ref_index_at(index);
2188 }
2189 JVM_END
2190 
2191 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetNameAndTypeRefIndexAt, JVM_ConstantPoolGetNameAndTypeRefIndexAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2192 {
2193   JvmtiVMObjectAllocEventCollector oam;
2194   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2195   bounds_check(cp, index, CHECK_0);
2196   constantTag tag = cp->tag_at(index);
2197   if (!tag.is_invoke_dynamic() && !tag.is_field_or_method()) {
2198     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2199   }
2200   return (jint) cp->uncached_name_and_type_ref_index_at(index);
2201 }
2202 JVM_END
2203 
2204 JVM_ENTRY_PROF(jobjectArray, JVM_ConstantPoolGetNameAndTypeRefInfoAt, JVM_ConstantPoolGetNameAndTypeRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2205 {
2206   JvmtiVMObjectAllocEventCollector oam;
2207   constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2208   bounds_check(cp, index, CHECK_NULL);
2209   constantTag tag = cp->tag_at(index);
2210   if (!tag.is_name_and_type()) {
2211     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2212   }
2213   Symbol* member_name = cp->symbol_at(cp->name_ref_index_at(index));
2214   Symbol* member_sig = cp->symbol_at(cp->signature_ref_index_at(index));
2215   objArrayOop dest_o = oopFactory::new_objArray(vmClasses::String_klass(), 2, CHECK_NULL);
2216   objArrayHandle dest(THREAD, dest_o);
2217   Handle str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2218   dest->obj_at_put(0, str());
2219   str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2220   dest->obj_at_put(1, str());
2221   return (jobjectArray) JNIHandles::make_local(THREAD, dest());
2222 }
2223 JVM_END
2224 
2225 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetIntAt, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2226 {
2227   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2228   bounds_check(cp, index, CHECK_0);
2229   constantTag tag = cp->tag_at(index);
2230   if (!tag.is_int()) {
2231     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2232   }
2233   return cp->int_at(index);
2234 }
2235 JVM_END
2236 
2237 JVM_ENTRY_PROF(jlong, JVM_ConstantPoolGetLongAt, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2238 {
2239   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2240   bounds_check(cp, index, CHECK_(0L));
2241   constantTag tag = cp->tag_at(index);
2242   if (!tag.is_long()) {
2243     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2244   }
2245   return cp->long_at(index);
2246 }
2247 JVM_END
2248 
2249 JVM_ENTRY_PROF(jfloat, JVM_ConstantPoolGetFloatAt, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2250 {
2251   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2252   bounds_check(cp, index, CHECK_(0.0f));
2253   constantTag tag = cp->tag_at(index);
2254   if (!tag.is_float()) {
2255     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2256   }
2257   return cp->float_at(index);
2258 }
2259 JVM_END
2260 
2261 JVM_ENTRY_PROF(jdouble, JVM_ConstantPoolGetDoubleAt, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2262 {
2263   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2264   bounds_check(cp, index, CHECK_(0.0));
2265   constantTag tag = cp->tag_at(index);
2266   if (!tag.is_double()) {
2267     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2268   }
2269   return cp->double_at(index);
2270 }
2271 JVM_END
2272 
2273 JVM_ENTRY_PROF(jstring, JVM_ConstantPoolGetStringAt, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2274 {
2275   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2276   bounds_check(cp, index, CHECK_NULL);
2277   constantTag tag = cp->tag_at(index);
2278   if (!tag.is_string()) {
2279     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2280   }
2281   oop str = cp->string_at(index, CHECK_NULL);
2282   return (jstring) JNIHandles::make_local(THREAD, str);
2283 }
2284 JVM_END
2285 
2286 JVM_ENTRY_PROF(jstring, JVM_ConstantPoolGetUTF8At, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2287 {
2288   JvmtiVMObjectAllocEventCollector oam;
2289   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2290   bounds_check(cp, index, CHECK_NULL);
2291   constantTag tag = cp->tag_at(index);
2292   if (!tag.is_symbol()) {
2293     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2294   }
2295   Symbol* sym = cp->symbol_at(index);
2296   Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2297   return (jstring) JNIHandles::make_local(THREAD, str());
2298 }
2299 JVM_END
2300 
2301 JVM_ENTRY_PROF(jbyte, JVM_ConstantPoolGetTagAt, JVM_ConstantPoolGetTagAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2302 {
2303   constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2304   bounds_check(cp, index, CHECK_0);
2305   constantTag tag = cp->tag_at(index);
2306   jbyte result = tag.value();
2307   // If returned tag values are not from the JVM spec, e.g. tags from 100 to 105,
2308   // they are changed to the corresponding tags from the JVM spec, so that java code in
2309   // sun.reflect.ConstantPool will return only tags from the JVM spec, not internal ones.
2310   if (tag.is_klass_or_reference()) {
2311       result = JVM_CONSTANT_Class;
2312   } else if (tag.is_string_index()) {
2313       result = JVM_CONSTANT_String;
2314   } else if (tag.is_method_type_in_error()) {
2315       result = JVM_CONSTANT_MethodType;
2316   } else if (tag.is_method_handle_in_error()) {
2317       result = JVM_CONSTANT_MethodHandle;
2318   } else if (tag.is_dynamic_constant_in_error()) {
2319       result = JVM_CONSTANT_Dynamic;
2320   }
2321   return result;
2322 }
2323 JVM_END
2324 
2325 // Assertion support. //////////////////////////////////////////////////////////
2326 
2327 JVM_ENTRY_PROF(jboolean, JVM_DesiredAssertionStatus, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2328   assert(cls != nullptr, "bad class");
2329 
2330   oop r = JNIHandles::resolve(cls);
2331   assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2332   if (java_lang_Class::is_primitive(r)) return false;
2333 
2334   Klass* k = java_lang_Class::as_Klass(r);
2335   assert(k->is_instance_klass(), "must be an instance klass");
2336   if (!k->is_instance_klass()) return false;
2337 
2338   ResourceMark rm(THREAD);
2339   const char* name = k->name()->as_C_string();
2340   bool system_class = k->class_loader() == nullptr;
2341   return JavaAssertions::enabled(name, system_class);
2342 
2343 JVM_END
2344 
2345 
2346 // Return a new AssertionStatusDirectives object with the fields filled in with
2347 // command-line assertion arguments (i.e., -ea, -da).
2348 JVM_ENTRY_PROF(jobject, JVM_AssertionStatusDirectives, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2349   JvmtiVMObjectAllocEventCollector oam;
2350   oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2351   return JNIHandles::make_local(THREAD, asd);
2352 JVM_END
2353 
2354 // Verification ////////////////////////////////////////////////////////////////////////////////
2355 
2356 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2357 
2358 // RedefineClasses support: bug 6214132 caused verification to fail.
2359 // All functions from this section should call the jvmtiThreadSate function:
2360 //   Klass* class_to_verify_considering_redefinition(Klass* klass).
2361 // The function returns a Klass* of the _scratch_class if the verifier
2362 // was invoked in the middle of the class redefinition.
2363 // Otherwise it returns its argument value which is the _the_class Klass*.
2364 // Please, refer to the description in the jvmtiThreadSate.hpp.
2365 
2366 JVM_ENTRY_PROF(const char*, JVM_GetClassNameUTF, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2367   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2368   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2369   return k->name()->as_utf8();
2370 JVM_END
2371 
2372 
2373 JVM_ENTRY_PROF(void, JVM_GetClassCPTypes, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2374   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2375   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2376   // types will have length zero if this is not an InstanceKlass
2377   // (length is determined by call to JVM_GetClassCPEntriesCount)
2378   if (k->is_instance_klass()) {
2379     ConstantPool* cp = InstanceKlass::cast(k)->constants();
2380     for (int index = cp->length() - 1; index >= 0; index--) {
2381       constantTag tag = cp->tag_at(index);
2382       types[index] = (tag.is_unresolved_klass()) ? (unsigned char) JVM_CONSTANT_Class : tag.value();
2383     }
2384   }
2385 JVM_END
2386 
2387 
2388 JVM_ENTRY_PROF(jint, JVM_GetClassCPEntriesCount, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2389   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2390   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2391   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->constants()->length();
2392 JVM_END
2393 
2394 
2395 JVM_ENTRY_PROF(jint, JVM_GetClassFieldsCount, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2396   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2397   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2398   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->java_fields_count();
2399 JVM_END
2400 
2401 
2402 JVM_ENTRY_PROF(jint, JVM_GetClassMethodsCount, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2403   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2404   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2405   return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->methods()->length();
2406 JVM_END
2407 
2408 
2409 // The following methods, used for the verifier, are never called with
2410 // array klasses, so a direct cast to InstanceKlass is safe.
2411 // Typically, these methods are called in a loop with bounds determined
2412 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2413 // zero for arrays.
2414 JVM_ENTRY_PROF(void, JVM_GetMethodIxExceptionIndexes, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2415   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2416   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2417   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2418   int length = method->checked_exceptions_length();
2419   if (length > 0) {
2420     CheckedExceptionElement* table= method->checked_exceptions_start();
2421     for (int i = 0; i < length; i++) {
2422       exceptions[i] = table[i].class_cp_index;
2423     }
2424   }
2425 JVM_END
2426 
2427 
2428 JVM_ENTRY_PROF(jint, JVM_GetMethodIxExceptionsCount, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2429   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2430   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2431   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2432   return method->checked_exceptions_length();
2433 JVM_END
2434 
2435 
2436 JVM_ENTRY_PROF(void, JVM_GetMethodIxByteCode, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2437   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2438   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2439   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2440   memcpy(code, method->code_base(), method->code_size());
2441 JVM_END
2442 
2443 
2444 JVM_ENTRY_PROF(jint, JVM_GetMethodIxByteCodeLength, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2445   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2446   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2447   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2448   return method->code_size();
2449 JVM_END
2450 
2451 
2452 JVM_ENTRY_PROF(void, JVM_GetMethodIxExceptionTableEntry, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2453   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2454   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2455   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2456   ExceptionTable extable(method);
2457   entry->start_pc   = extable.start_pc(entry_index);
2458   entry->end_pc     = extable.end_pc(entry_index);
2459   entry->handler_pc = extable.handler_pc(entry_index);
2460   entry->catchType  = extable.catch_type_index(entry_index);
2461 JVM_END
2462 
2463 
2464 JVM_ENTRY_PROF(jint, JVM_GetMethodIxExceptionTableLength, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2465   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2466   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2467   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2468   return method->exception_table_length();
2469 JVM_END
2470 
2471 
2472 JVM_ENTRY_PROF(jint, JVM_GetMethodIxModifiers, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2473   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2474   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2475   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2476   return method->access_flags().as_method_flags();
2477 JVM_END
2478 
2479 
2480 JVM_ENTRY_PROF(jint, JVM_GetFieldIxModifiers, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2481   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2482   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2483   return InstanceKlass::cast(k)->field_access_flags(field_index);
2484 JVM_END
2485 
2486 
2487 JVM_ENTRY_PROF(jint, JVM_GetMethodIxLocalsCount, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2488   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2489   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2490   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2491   return method->max_locals();
2492 JVM_END
2493 
2494 
2495 JVM_ENTRY_PROF(jint, JVM_GetMethodIxArgsSize, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2496   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2497   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2498   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2499   return method->size_of_parameters();
2500 JVM_END
2501 
2502 
2503 JVM_ENTRY_PROF(jint, JVM_GetMethodIxMaxStack, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2504   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2505   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2506   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2507   return method->verifier_max_stack();
2508 JVM_END
2509 
2510 
2511 JVM_ENTRY_PROF(jboolean, JVM_IsConstructorIx, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2512   ResourceMark rm(THREAD);
2513   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2514   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2515   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2516   return method->name() == vmSymbols::object_initializer_name();
2517 JVM_END
2518 
2519 
2520 JVM_ENTRY_PROF(jboolean, JVM_IsVMGeneratedMethodIx, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2521   ResourceMark rm(THREAD);
2522   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2523   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2524   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2525   return method->is_overpass();
2526 JVM_END
2527 
2528 JVM_ENTRY_PROF(const char*, JVM_GetMethodIxNameUTF, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2529   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2530   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2531   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2532   return method->name()->as_utf8();
2533 JVM_END
2534 
2535 
2536 JVM_ENTRY_PROF(const char*, JVM_GetMethodIxSignatureUTF, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2537   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2538   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2539   Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2540   return method->signature()->as_utf8();
2541 JVM_END
2542 
2543 /**
2544  * All of these JVM_GetCP-xxx methods are used by the old verifier to
2545  * read entries in the constant pool.  Since the old verifier always
2546  * works on a copy of the code, it will not see any rewriting that
2547  * may possibly occur in the middle of verification.  So it is important
2548  * that nothing it calls tries to use the cpCache instead of the raw
2549  * constant pool, so we must use cp->uncached_x methods when appropriate.
2550  */
2551 JVM_ENTRY_PROF(const char*, JVM_GetCPFieldNameUTF, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2552   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2553   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2554   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2555   switch (cp->tag_at(cp_index).value()) {
2556     case JVM_CONSTANT_Fieldref:
2557       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2558     default:
2559       fatal("JVM_GetCPFieldNameUTF: illegal constant");
2560   }
2561   ShouldNotReachHere();
2562   return nullptr;
2563 JVM_END
2564 
2565 
2566 JVM_ENTRY_PROF(const char*, JVM_GetCPMethodNameUTF, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2567   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2568   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2569   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2570   switch (cp->tag_at(cp_index).value()) {
2571     case JVM_CONSTANT_InterfaceMethodref:
2572     case JVM_CONSTANT_Methodref:
2573       return cp->uncached_name_ref_at(cp_index)->as_utf8();
2574     default:
2575       fatal("JVM_GetCPMethodNameUTF: illegal constant");
2576   }
2577   ShouldNotReachHere();
2578   return nullptr;
2579 JVM_END
2580 
2581 
2582 JVM_ENTRY_PROF(const char*, JVM_GetCPMethodSignatureUTF, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2583   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2584   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2585   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2586   switch (cp->tag_at(cp_index).value()) {
2587     case JVM_CONSTANT_InterfaceMethodref:
2588     case JVM_CONSTANT_Methodref:
2589       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2590     default:
2591       fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2592   }
2593   ShouldNotReachHere();
2594   return nullptr;
2595 JVM_END
2596 
2597 
2598 JVM_ENTRY_PROF(const char*, JVM_GetCPFieldSignatureUTF, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2599   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2600   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2601   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2602   switch (cp->tag_at(cp_index).value()) {
2603     case JVM_CONSTANT_Fieldref:
2604       return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2605     default:
2606       fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2607   }
2608   ShouldNotReachHere();
2609   return nullptr;
2610 JVM_END
2611 
2612 
2613 JVM_ENTRY_PROF(const char*, JVM_GetCPClassNameUTF, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2614   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2615   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2616   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2617   Symbol* classname = cp->klass_name_at(cp_index);
2618   return classname->as_utf8();
2619 JVM_END
2620 
2621 
2622 JVM_ENTRY_PROF(const char*, JVM_GetCPFieldClassNameUTF, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2623   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2624   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2625   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2626   switch (cp->tag_at(cp_index).value()) {
2627     case JVM_CONSTANT_Fieldref: {
2628       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2629       Symbol* classname = cp->klass_name_at(class_index);
2630       return classname->as_utf8();
2631     }
2632     default:
2633       fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2634   }
2635   ShouldNotReachHere();
2636   return nullptr;
2637 JVM_END
2638 
2639 
2640 JVM_ENTRY_PROF(const char*, JVM_GetCPMethodClassNameUTF, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2641   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2642   k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2643   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2644   switch (cp->tag_at(cp_index).value()) {
2645     case JVM_CONSTANT_Methodref:
2646     case JVM_CONSTANT_InterfaceMethodref: {
2647       int class_index = cp->uncached_klass_ref_index_at(cp_index);
2648       Symbol* classname = cp->klass_name_at(class_index);
2649       return classname->as_utf8();
2650     }
2651     default:
2652       fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2653   }
2654   ShouldNotReachHere();
2655   return nullptr;
2656 JVM_END
2657 
2658 
2659 JVM_ENTRY_PROF(jint, JVM_GetCPFieldModifiers, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2660   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2661   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2662   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2663   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2664   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2665   ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2666   switch (cp->tag_at(cp_index).value()) {
2667     case JVM_CONSTANT_Fieldref: {
2668       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2669       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2670       InstanceKlass* ik = InstanceKlass::cast(k_called);
2671       for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
2672         if (fs.name() == name && fs.signature() == signature) {
2673           return fs.access_flags().as_field_flags();
2674         }
2675       }
2676       return -1;
2677     }
2678     default:
2679       fatal("JVM_GetCPFieldModifiers: illegal constant");
2680   }
2681   ShouldNotReachHere();
2682   return 0;
2683 JVM_END
2684 
2685 
2686 JVM_ENTRY_PROF(jint, JVM_GetCPMethodModifiers, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2687   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2688   Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2689   k        = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2690   k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2691   ConstantPool* cp = InstanceKlass::cast(k)->constants();
2692   switch (cp->tag_at(cp_index).value()) {
2693     case JVM_CONSTANT_Methodref:
2694     case JVM_CONSTANT_InterfaceMethodref: {
2695       Symbol* name      = cp->uncached_name_ref_at(cp_index);
2696       Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2697       Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2698       int methods_count = methods->length();
2699       for (int i = 0; i < methods_count; i++) {
2700         Method* method = methods->at(i);
2701         if (method->name() == name && method->signature() == signature) {
2702             return method->access_flags().as_method_flags();
2703         }
2704       }
2705       return -1;
2706     }
2707     default:
2708       fatal("JVM_GetCPMethodModifiers: illegal constant");
2709   }
2710   ShouldNotReachHere();
2711   return 0;
2712 JVM_END
2713 
2714 
2715 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2716 
2717 JVM_LEAF_PROF(void, JVM_ReleaseUTF, JVM_ReleaseUTF(const char *utf))
2718   // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2719 JVM_END
2720 
2721 
2722 JVM_ENTRY_PROF(jboolean, JVM_IsSameClassPackage, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2723   oop class1_mirror = JNIHandles::resolve_non_null(class1);
2724   oop class2_mirror = JNIHandles::resolve_non_null(class2);
2725   Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2726   Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2727   return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2728 JVM_END
2729 
2730 // Printing support //////////////////////////////////////////////////
2731 extern "C" {
2732 
2733 ATTRIBUTE_PRINTF(3, 0)
2734 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2735   // Reject count values that are negative signed values converted to
2736   // unsigned; see bug 4399518, 4417214
2737   if ((intptr_t)count <= 0) return -1;
2738 
2739   int result = os::vsnprintf(str, count, fmt, args);
2740   if (result > 0 && (size_t)result >= count) {
2741     result = -1;
2742   }
2743 
2744   return result;
2745 }
2746 
2747 ATTRIBUTE_PRINTF(3, 4)
2748 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2749   va_list args;
2750   int len;
2751   va_start(args, fmt);
2752   len = jio_vsnprintf(str, count, fmt, args);
2753   va_end(args);
2754   return len;
2755 }
2756 
2757 ATTRIBUTE_PRINTF(2, 3)
2758 int jio_fprintf(FILE* f, const char *fmt, ...) {
2759   int len;
2760   va_list args;
2761   va_start(args, fmt);
2762   len = jio_vfprintf(f, fmt, args);
2763   va_end(args);
2764   return len;
2765 }
2766 
2767 ATTRIBUTE_PRINTF(2, 0)
2768 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2769   if (Arguments::vfprintf_hook() != nullptr) {
2770      return Arguments::vfprintf_hook()(f, fmt, args);
2771   } else {
2772     return vfprintf(f, fmt, args);
2773   }
2774 }
2775 
2776 ATTRIBUTE_PRINTF(1, 2)
2777 JNIEXPORT int jio_printf(const char *fmt, ...) {
2778   int len;
2779   va_list args;
2780   va_start(args, fmt);
2781   len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2782   va_end(args);
2783   return len;
2784 }
2785 
2786 // HotSpot specific jio method
2787 void jio_print(const char* s, size_t len) {
2788   // Try to make this function as atomic as possible.
2789   if (Arguments::vfprintf_hook() != nullptr) {
2790     jio_fprintf(defaultStream::output_stream(), "%.*s", (int)len, s);
2791   } else {
2792     // Make an unused local variable to avoid warning from gcc compiler.
2793     bool dummy = os::write(defaultStream::output_fd(), s, len);
2794   }
2795 }
2796 
2797 } // Extern C
2798 
2799 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2800 
2801 // In most of the JVM thread support functions we need to access the
2802 // thread through a ThreadsListHandle to prevent it from exiting and
2803 // being reclaimed while we try to operate on it. The exceptions to this
2804 // rule are when operating on the current thread, or if the monitor of
2805 // the target java.lang.Thread is locked at the Java level - in both
2806 // cases the target cannot exit.
2807 
2808 static void thread_entry(JavaThread* thread, TRAPS) {
2809   HandleMark hm(THREAD);
2810   Handle obj(THREAD, thread->threadObj());
2811   JavaValue result(T_VOID);
2812   JavaCalls::call_virtual(&result,
2813                           obj,
2814                           vmClasses::Thread_klass(),
2815                           vmSymbols::run_method_name(),
2816                           vmSymbols::void_method_signature(),
2817                           THREAD);
2818 }
2819 
2820 
2821 JVM_ENTRY_PROF(void, JVM_StartThread, JVM_StartThread(JNIEnv* env, jobject jthread))
2822 #if INCLUDE_CDS
2823   if (CDSConfig::allow_only_single_java_thread()) {
2824     // During java -Xshare:dump, if we allow multiple Java threads to
2825     // execute in parallel, symbols and classes may be loaded in
2826     // random orders which will make the resulting CDS archive
2827     // non-deterministic.
2828     //
2829     // Lucikly, during java -Xshare:dump, it's important to run only
2830     // the code in the main Java thread (which is NOT started here) that
2831     // creates the module graph, etc. It's safe to not start the other
2832     // threads which are launched by class static initializers
2833     // (ReferenceHandler, FinalizerThread and CleanerImpl).
2834     if (log_is_enabled(Info, cds)) {
2835       ResourceMark rm;
2836       oop t = JNIHandles::resolve_non_null(jthread);
2837       log_info(cds)("JVM_StartThread() ignored: %s", t->klass()->external_name());
2838     }
2839     return;
2840   }
2841 #endif
2842   JavaThread *native_thread = nullptr;
2843 
2844   // We cannot hold the Threads_lock when we throw an exception,
2845   // due to rank ordering issues. Example:  we might need to grab the
2846   // Heap_lock while we construct the exception.
2847   bool throw_illegal_thread_state = false;
2848 
2849   // We must release the Threads_lock before we can post a jvmti event
2850   // in Thread::start.
2851   {
2852     ConditionalMutexLocker throttle_ml(ThreadsLockThrottle_lock, UseThreadsLockThrottleLock);
2853     // Ensure that the C++ Thread and OSThread structures aren't freed before
2854     // we operate.
2855     MutexLocker ml(Threads_lock);
2856 
2857     // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2858     // re-starting an already started thread, so we should usually find
2859     // that the JavaThread is null. However for a JNI attached thread
2860     // there is a small window between the Thread object being created
2861     // (with its JavaThread set) and the update to its threadStatus, so we
2862     // have to check for this
2863     if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != nullptr) {
2864       throw_illegal_thread_state = true;
2865     } else {
2866       jlong size =
2867              java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2868       // Allocate the C++ Thread structure and create the native thread.  The
2869       // stack size retrieved from java is 64-bit signed, but the constructor takes
2870       // size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.
2871       //  - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.
2872       //  - Avoid passing negative values which would result in really large stacks.
2873       NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)
2874       size_t sz = size > 0 ? (size_t) size : 0;
2875       native_thread = new JavaThread(&thread_entry, sz);
2876 
2877       // At this point it may be possible that no osthread was created for the
2878       // JavaThread due to lack of memory. Check for this situation and throw
2879       // an exception if necessary. Eventually we may want to change this so
2880       // that we only grab the lock if the thread was created successfully -
2881       // then we can also do this check and throw the exception in the
2882       // JavaThread constructor.
2883       if (native_thread->osthread() != nullptr) {
2884         // Note: the current thread is not being used within "prepare".
2885         native_thread->prepare(jthread);
2886       }
2887     }
2888   }
2889 
2890   if (throw_illegal_thread_state) {
2891     THROW(vmSymbols::java_lang_IllegalThreadStateException());
2892   }
2893 
2894   assert(native_thread != nullptr, "Starting null thread?");
2895 
2896   if (native_thread->osthread() == nullptr) {
2897     ResourceMark rm(thread);
2898     log_warning(os, thread)("Failed to start the native thread for java.lang.Thread \"%s\"",
2899                             JavaThread::name_for(JNIHandles::resolve_non_null(jthread)));
2900     // No one should hold a reference to the 'native_thread'.
2901     native_thread->smr_delete();
2902     if (JvmtiExport::should_post_resource_exhausted()) {
2903       JvmtiExport::post_resource_exhausted(
2904         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2905         os::native_thread_creation_failed_msg());
2906     }
2907     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2908               os::native_thread_creation_failed_msg());
2909   }
2910 
2911   JFR_ONLY(Jfr::on_java_thread_start(thread, native_thread);)
2912 
2913   Thread::start(native_thread);
2914 
2915 JVM_END
2916 
2917 
2918 JVM_ENTRY_PROF(void, JVM_SetThreadPriority, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2919   ThreadsListHandle tlh(thread);
2920   oop java_thread = nullptr;
2921   JavaThread* receiver = nullptr;
2922   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
2923   java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2924 
2925   if (is_alive) {
2926     // jthread refers to a live JavaThread.
2927     Thread::set_priority(receiver, (ThreadPriority)prio);
2928   }
2929   // Implied else: If the JavaThread hasn't started yet, then the
2930   // priority set in the java.lang.Thread object above will be pushed
2931   // down when it does start.
2932 JVM_END
2933 
2934 
2935 JVM_LEAF_PROF(void, JVM_Yield, JVM_Yield(JNIEnv *env, jclass threadClass))
2936   HOTSPOT_THREAD_YIELD();
2937   os::naked_yield();
2938 JVM_END
2939 
2940 JVM_ENTRY_PROF(void, JVM_SleepNanos, JVM_SleepNanos(JNIEnv* env, jclass threadClass, jlong nanos))
2941   if (nanos < 0) {
2942     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nanosecond timeout value out of range");
2943   }
2944 
2945   if (thread->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
2946     THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2947   }
2948 
2949   // Save current thread state and restore it at the end of this block.
2950   // And set new thread state to SLEEPING.
2951   JavaThreadSleepState jtss(thread);
2952 
2953   HOTSPOT_THREAD_SLEEP_BEGIN(nanos / NANOSECS_PER_MILLISEC);
2954 
2955   if (nanos == 0) {
2956     os::naked_yield();
2957   } else {
2958     ThreadState old_state = thread->osthread()->get_state();
2959     thread->osthread()->set_state(SLEEPING);
2960     if (!thread->sleep_nanos(nanos)) { // interrupted
2961       // An asynchronous exception could have been thrown on
2962       // us while we were sleeping. We do not overwrite those.
2963       if (!HAS_PENDING_EXCEPTION) {
2964         HOTSPOT_THREAD_SLEEP_END(1);
2965 
2966         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
2967         // to properly restore the thread state.  That's likely wrong.
2968         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2969       }
2970     }
2971     thread->osthread()->set_state(old_state);
2972   }
2973   HOTSPOT_THREAD_SLEEP_END(0);
2974 JVM_END
2975 
2976 JVM_ENTRY_PROF(jobject, JVM_CurrentCarrierThread, JVM_CurrentCarrierThread(JNIEnv* env, jclass threadClass))
2977   oop jthread = thread->threadObj();
2978   assert(jthread != nullptr, "no current carrier thread!");
2979   return JNIHandles::make_local(THREAD, jthread);
2980 JVM_END
2981 
2982 JVM_ENTRY_PROF(jobject, JVM_CurrentThread, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
2983   oop theThread = thread->vthread();
2984   assert(theThread != (oop)nullptr, "no current thread!");
2985   return JNIHandles::make_local(THREAD, theThread);
2986 JVM_END
2987 
2988 JVM_ENTRY_PROF(void, JVM_SetCurrentThread, JVM_SetCurrentThread(JNIEnv* env, jobject thisThread,
2989                                      jobject theThread))
2990   oop threadObj = JNIHandles::resolve(theThread);
2991   thread->set_vthread(threadObj);
2992 
2993   // Set _monitor_owner_id of new current Thread
2994   thread->set_monitor_owner_id(java_lang_Thread::thread_id(threadObj));
2995 
2996   JFR_ONLY(Jfr::on_set_current_thread(thread, threadObj);)
2997 JVM_END
2998 
2999 JVM_ENTRY_PROF(jlong, JVM_GetNextThreadIdOffset, JVM_GetNextThreadIdOffset(JNIEnv* env, jclass threadClass))
3000   return ThreadIdentifier::unsafe_offset();
3001 JVM_END
3002 
3003 JVM_ENTRY_PROF(void, JVM_Interrupt, JVM_Interrupt(JNIEnv* env, jobject jthread))
3004   ThreadsListHandle tlh(thread);
3005   JavaThread* receiver = nullptr;
3006   bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, nullptr);
3007   if (is_alive) {
3008     // jthread refers to a live JavaThread.
3009     receiver->interrupt();
3010   }
3011 JVM_END
3012 
3013 // Return true iff the current thread has locked the object passed in
3014 
3015 JVM_ENTRY_PROF(jboolean, JVM_HoldsLock, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3016   if (obj == nullptr) {
3017     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3018   }
3019   Handle h_obj(THREAD, JNIHandles::resolve(obj));
3020   return ObjectSynchronizer::current_thread_holds_lock(thread, h_obj);
3021 JVM_END
3022 
3023 JVM_ENTRY_PROF(jobject, JVM_GetStackTrace, JVM_GetStackTrace(JNIEnv *env, jobject jthread))
3024   oop trace = java_lang_Thread::async_get_stack_trace(JNIHandles::resolve(jthread), THREAD);
3025   return JNIHandles::make_local(THREAD, trace);
3026 JVM_END
3027 
3028 
3029 JVM_ENTRY_PROF(void, JVM_SetNativeThreadName, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3030   // We don't use a ThreadsListHandle here because the current thread
3031   // must be alive.
3032   oop java_thread = JNIHandles::resolve_non_null(jthread);
3033   JavaThread* thr = java_lang_Thread::thread(java_thread);
3034   if (thread == thr && !thr->has_attached_via_jni()) {
3035     // Thread naming is only supported for the current thread and
3036     // we don't set the name of an attached thread to avoid stepping
3037     // on other programs.
3038     ResourceMark rm(thread);
3039     const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3040     os::set_native_thread_name(thread_name);
3041   }
3042 JVM_END
3043 
3044 JVM_ENTRY_PROF(jobject, JVM_ScopedValueCache, JVM_ScopedValueCache(JNIEnv* env, jclass threadClass))
3045   oop theCache = thread->scopedValueCache();
3046   return JNIHandles::make_local(THREAD, theCache);
3047 JVM_END
3048 
3049 JVM_ENTRY_PROF(void, JVM_SetScopedValueCache, JVM_SetScopedValueCache(JNIEnv* env, jclass threadClass,
3050                                        jobject theCache))
3051   arrayOop objs = arrayOop(JNIHandles::resolve(theCache));
3052   thread->set_scopedValueCache(objs);
3053 JVM_END
3054 
3055 // java.lang.Package ////////////////////////////////////////////////////////////////
3056 
3057 
3058 JVM_ENTRY_PROF(jstring, JVM_GetSystemPackage, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3059   ResourceMark rm(THREAD);
3060   JvmtiVMObjectAllocEventCollector oam;
3061   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3062   oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3063 return (jstring) JNIHandles::make_local(THREAD, result);
3064 JVM_END
3065 
3066 
3067 JVM_ENTRY_PROF(jobjectArray, JVM_GetSystemPackages, JVM_GetSystemPackages(JNIEnv *env))
3068   JvmtiVMObjectAllocEventCollector oam;
3069   objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3070   return (jobjectArray) JNIHandles::make_local(THREAD, result);
3071 JVM_END
3072 
3073 
3074 // java.lang.ref.Reference ///////////////////////////////////////////////////////////////
3075 
3076 
3077 JVM_ENTRY_PROF(jobject, JVM_GetAndClearReferencePendingList, JVM_GetAndClearReferencePendingList(JNIEnv* env))
3078   MonitorLocker ml(Heap_lock);
3079   oop ref = Universe::reference_pending_list();
3080   if (ref != nullptr) {
3081     Universe::clear_reference_pending_list();
3082   }
3083   return JNIHandles::make_local(THREAD, ref);
3084 JVM_END
3085 
3086 JVM_ENTRY_PROF(jboolean, JVM_HasReferencePendingList, JVM_HasReferencePendingList(JNIEnv* env))
3087   MonitorLocker ml(Heap_lock);
3088   return Universe::has_reference_pending_list();
3089 JVM_END
3090 
3091 JVM_ENTRY_PROF(void, JVM_WaitForReferencePendingList, JVM_WaitForReferencePendingList(JNIEnv* env))
3092   MonitorLocker ml(Heap_lock);
3093   while (!Universe::has_reference_pending_list()) {
3094     ml.wait();
3095   }
3096 JVM_END
3097 
3098 JVM_ENTRY_PROF(jboolean, JVM_ReferenceRefersTo, JVM_ReferenceRefersTo(JNIEnv* env, jobject ref, jobject o))
3099   oop ref_oop = JNIHandles::resolve_non_null(ref);
3100   // PhantomReference has it's own implementation of refersTo().
3101   // See: JVM_PhantomReferenceRefersTo
3102   assert(!java_lang_ref_Reference::is_phantom(ref_oop), "precondition");
3103   oop referent = java_lang_ref_Reference::weak_referent_no_keepalive(ref_oop);
3104   return referent == JNIHandles::resolve(o);
3105 JVM_END
3106 
3107 JVM_ENTRY_PROF(void, JVM_ReferenceClear, JVM_ReferenceClear(JNIEnv* env, jobject ref))
3108   oop ref_oop = JNIHandles::resolve_non_null(ref);
3109   // FinalReference has it's own implementation of clear().
3110   assert(!java_lang_ref_Reference::is_final(ref_oop), "precondition");
3111   if (java_lang_ref_Reference::unknown_referent_no_keepalive(ref_oop) == nullptr) {
3112     // If the referent has already been cleared then done.
3113     // However, if the referent is dead but has not yet been cleared by
3114     // concurrent reference processing, it should NOT be cleared here.
3115     // Instead, clearing should be left to the GC.  Clearing it here could
3116     // detectably lose an expected notification, which is impossible with
3117     // STW reference processing.  The clearing in enqueue() doesn't have
3118     // this problem, since the enqueue covers the notification, but it's not
3119     // worth the effort to handle that case specially.
3120     return;
3121   }
3122   java_lang_ref_Reference::clear_referent(ref_oop);
3123 JVM_END
3124 
3125 
3126 // java.lang.ref.PhantomReference //////////////////////////////////////////////////
3127 
3128 
3129 JVM_ENTRY_PROF(jboolean, JVM_PhantomReferenceRefersTo, JVM_PhantomReferenceRefersTo(JNIEnv* env, jobject ref, jobject o))
3130   oop ref_oop = JNIHandles::resolve_non_null(ref);
3131   oop referent = java_lang_ref_Reference::phantom_referent_no_keepalive(ref_oop);
3132   return referent == JNIHandles::resolve(o);
3133 JVM_END
3134 
3135 
3136 // ObjectInputStream ///////////////////////////////////////////////////////////////
3137 
3138 // Return the first user-defined class loader up the execution stack, or null
3139 // if only code from the bootstrap or platform class loader is on the stack.
3140 
3141 JVM_ENTRY_PROF(jobject, JVM_LatestUserDefinedLoader, JVM_LatestUserDefinedLoader(JNIEnv *env))
3142   for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3143     InstanceKlass* ik = vfst.method()->method_holder();
3144     oop loader = ik->class_loader();
3145     if (loader != nullptr && !SystemDictionary::is_platform_class_loader(loader)) {
3146       return JNIHandles::make_local(THREAD, loader);
3147     }
3148   }
3149   return nullptr;
3150 JVM_END
3151 
3152 
3153 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3154 
3155 
3156 // resolve array handle and check arguments
3157 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3158   if (arr == nullptr) {
3159     THROW_NULL(vmSymbols::java_lang_NullPointerException());
3160   }
3161   oop a = JNIHandles::resolve_non_null(arr);
3162   if (!a->is_array()) {
3163     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3164   } else if (type_array_only && !a->is_typeArray()) {
3165     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3166   }
3167   return arrayOop(a);
3168 }
3169 
3170 
3171 JVM_ENTRY_PROF(jint, JVM_GetArrayLength, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3172   arrayOop a = check_array(env, arr, false, CHECK_0);
3173   return a->length();
3174 JVM_END
3175 
3176 
3177 JVM_ENTRY_PROF(jobject, JVM_GetArrayElement, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3178   JvmtiVMObjectAllocEventCollector oam;
3179   arrayOop a = check_array(env, arr, false, CHECK_NULL);
3180   jvalue value;
3181   BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3182   oop box = Reflection::box(&value, type, CHECK_NULL);
3183   return JNIHandles::make_local(THREAD, box);
3184 JVM_END
3185 
3186 
3187 JVM_ENTRY_PROF(jvalue, JVM_GetPrimitiveArrayElement, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3188   jvalue value;
3189   value.i = 0; // to initialize value before getting used in CHECK
3190   arrayOop a = check_array(env, arr, true, CHECK_(value));
3191   assert(a->is_typeArray(), "just checking");
3192   BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3193   BasicType wide_type = (BasicType) wCode;
3194   if (type != wide_type) {
3195     Reflection::widen(&value, type, wide_type, CHECK_(value));
3196   }
3197   return value;
3198 JVM_END
3199 
3200 
3201 JVM_ENTRY_PROF(void, JVM_SetArrayElement, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3202   arrayOop a = check_array(env, arr, false, CHECK);
3203   oop box = JNIHandles::resolve(val);
3204   jvalue value;
3205   value.i = 0; // to initialize value before getting used in CHECK
3206   BasicType value_type;
3207   if (a->is_objArray()) {
3208     // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3209     value_type = Reflection::unbox_for_regular_object(box, &value);
3210   } else {
3211     value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3212   }
3213   Reflection::array_set(&value, a, index, value_type, CHECK);
3214 JVM_END
3215 
3216 
3217 JVM_ENTRY_PROF(void, JVM_SetPrimitiveArrayElement, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3218   arrayOop a = check_array(env, arr, true, CHECK);
3219   assert(a->is_typeArray(), "just checking");
3220   BasicType value_type = (BasicType) vCode;
3221   Reflection::array_set(&v, a, index, value_type, CHECK);
3222 JVM_END
3223 
3224 
3225 JVM_ENTRY_PROF(jobject, JVM_NewArray, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3226   JvmtiVMObjectAllocEventCollector oam;
3227   oop element_mirror = JNIHandles::resolve(eltClass);
3228   oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3229   return JNIHandles::make_local(THREAD, result);
3230 JVM_END
3231 
3232 
3233 JVM_ENTRY_PROF(jobject, JVM_NewMultiArray, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3234   JvmtiVMObjectAllocEventCollector oam;
3235   arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3236   oop element_mirror = JNIHandles::resolve(eltClass);
3237   assert(dim_array->is_typeArray(), "just checking");
3238   oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3239   return JNIHandles::make_local(THREAD, result);
3240 JVM_END
3241 
3242 
3243 // Library support ///////////////////////////////////////////////////////////////////////////
3244 
3245 JVM_LEAF_PROF(void*, JVM_LoadZipLibrary, JVM_LoadZipLibrary())
3246   return ZipLibrary::handle();
3247 JVM_END
3248 
3249 JVM_ENTRY_NO_ENV_PROF(void*, JVM_LoadLibrary, JVM_LoadLibrary(const char* name, jboolean throwException))
3250   //%note jvm_ct
3251   char ebuf[1024];
3252   void *load_result;
3253   {
3254     ThreadToNativeFromVM ttnfvm(thread);
3255     load_result = os::dll_load(name, ebuf, sizeof ebuf);
3256   }
3257   if (load_result == nullptr) {
3258     if (throwException) {
3259       char msg[1024];
3260       jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3261       // Since 'ebuf' may contain a string encoded using
3262       // platform encoding scheme, we need to pass
3263       // Exceptions::unsafe_to_utf8 to the new_exception method
3264       // as the last argument. See bug 6367357.
3265       Handle h_exception =
3266         Exceptions::new_exception(thread,
3267                                   vmSymbols::java_lang_UnsatisfiedLinkError(),
3268                                   msg, Exceptions::unsafe_to_utf8);
3269 
3270       THROW_HANDLE_NULL(h_exception);
3271     } else {
3272       log_info(library)("Failed to load library %s", name);
3273       return load_result;
3274     }
3275   }
3276   log_info(library)("Loaded library %s, handle " INTPTR_FORMAT, name, p2i(load_result));
3277   return load_result;
3278 JVM_END
3279 
3280 
3281 JVM_LEAF_PROF(void, JVM_UnloadLibrary, JVM_UnloadLibrary(void* handle))
3282   os::dll_unload(handle);
3283   log_info(library)("Unloaded library with handle " INTPTR_FORMAT, p2i(handle));
3284 JVM_END
3285 
3286 
3287 JVM_LEAF_PROF(void*, JVM_FindLibraryEntry, JVM_FindLibraryEntry(void* handle, const char* name))
3288   void* find_result = os::dll_lookup(handle, name);
3289   log_info(library)("%s %s in library with handle " INTPTR_FORMAT,
3290                     find_result != nullptr ? "Found" : "Failed to find",
3291                     name, p2i(handle));
3292   return find_result;
3293 JVM_END
3294 
3295 
3296 // JNI version ///////////////////////////////////////////////////////////////////////////////
3297 
3298 JVM_LEAF_PROF(jboolean, JVM_IsSupportedJNIVersion, JVM_IsSupportedJNIVersion(jint version))
3299   return Threads::is_supported_jni_version_including_1_1(version);
3300 JVM_END
3301 
3302 
3303 JVM_LEAF_PROF(jboolean, JVM_IsPreviewEnabled, JVM_IsPreviewEnabled(void))
3304   return Arguments::enable_preview() ? JNI_TRUE : JNI_FALSE;
3305 JVM_END
3306 
3307 JVM_LEAF_PROF(jboolean, JVM_IsContinuationsSupported, JVM_IsContinuationsSupported(void))
3308   return VMContinuations ? JNI_TRUE : JNI_FALSE;
3309 JVM_END
3310 
3311 JVM_LEAF_PROF(jboolean, JVM_IsForeignLinkerSupported, JVM_IsForeignLinkerSupported(void))
3312   return ForeignGlobals::is_foreign_linker_supported() ? JNI_TRUE : JNI_FALSE;
3313 JVM_END
3314 
3315 JVM_LEAF(jboolean, JVM_IsStaticallyLinked(void))
3316   return is_vm_statically_linked() ? JNI_TRUE : JNI_FALSE;
3317 JVM_END
3318 
3319 // String support ///////////////////////////////////////////////////////////////////////////
3320 
3321 JVM_ENTRY_PROF(jstring, JVM_InternString, JVM_InternString(JNIEnv *env, jstring str))
3322   JvmtiVMObjectAllocEventCollector oam;
3323   if (str == nullptr) return nullptr;
3324   oop string = JNIHandles::resolve_non_null(str);
3325   oop result = StringTable::intern(string, CHECK_NULL);
3326   return (jstring) JNIHandles::make_local(THREAD, result);
3327 JVM_END
3328 
3329 
3330 // VM Raw monitor support //////////////////////////////////////////////////////////////////////
3331 
3332 // VM Raw monitors (not to be confused with JvmtiRawMonitors) are a simple mutual exclusion
3333 // lock (not actually monitors: no wait/notify) that is exported by the VM for use by JDK
3334 // library code. They may be used by JavaThreads and non-JavaThreads and do not participate
3335 // in the safepoint protocol, thread suspension, thread interruption, or most things of that
3336 // nature, except JavaThreads will be blocked by VM_Exit::block_if_vm_exited if the VM has
3337 // shutdown. JavaThreads will be "in native" when using this API from JDK code.
3338 
3339 
3340 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3341   VM_Exit::block_if_vm_exited();
3342   return new PlatformMutex();
3343 }
3344 
3345 
3346 JNIEXPORT void JNICALL  JVM_RawMonitorDestroy(void *mon) {
3347   VM_Exit::block_if_vm_exited();
3348   delete ((PlatformMutex*) mon);
3349 }
3350 
3351 
3352 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3353   VM_Exit::block_if_vm_exited();
3354   ((PlatformMutex*) mon)->lock();
3355   return 0;
3356 }
3357 
3358 
3359 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3360   VM_Exit::block_if_vm_exited();
3361   ((PlatformMutex*) mon)->unlock();
3362 }
3363 
3364 
3365 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3366 
3367 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3368                                     Handle loader, jboolean throwError, TRAPS) {
3369   Klass* klass = SystemDictionary::resolve_or_fail(name, loader, throwError != 0, CHECK_NULL);
3370 
3371   // Check if we should initialize the class
3372   if (init && klass->is_instance_klass()) {
3373     klass->initialize(CHECK_NULL);
3374   }
3375   return (jclass) JNIHandles::make_local(THREAD, klass->java_mirror());
3376 }
3377 
3378 
3379 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3380 
3381 JVM_ENTRY_PROF(jobject, JVM_InvokeMethod, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3382   Handle method_handle;
3383   if (thread->stack_overflow_state()->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3384     method_handle = Handle(THREAD, JNIHandles::resolve(method));
3385     Handle receiver(THREAD, JNIHandles::resolve(obj));
3386     objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3387     oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3388     jobject res = JNIHandles::make_local(THREAD, result);
3389     if (JvmtiExport::should_post_vm_object_alloc()) {
3390       oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3391       assert(ret_type != nullptr, "sanity check: ret_type oop must not be null!");
3392       if (java_lang_Class::is_primitive(ret_type)) {
3393         // Only for primitive type vm allocates memory for java object.
3394         // See box() method.
3395         JvmtiExport::post_vm_object_alloc(thread, result);
3396       }
3397     }
3398     return res;
3399   } else {
3400     THROW_NULL(vmSymbols::java_lang_StackOverflowError());
3401   }
3402 JVM_END
3403 
3404 
3405 JVM_ENTRY_PROF(jobject, JVM_NewInstanceFromConstructor, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3406   oop constructor_mirror = JNIHandles::resolve(c);
3407   objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3408   oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3409   jobject res = JNIHandles::make_local(THREAD, result);
3410   if (JvmtiExport::should_post_vm_object_alloc()) {
3411     JvmtiExport::post_vm_object_alloc(thread, result);
3412   }
3413   return res;
3414 JVM_END
3415 
3416 JVM_ENTRY_PROF(void, JVM_InitializeFromArchive, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
3417   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3418   assert(k->is_klass(), "just checking");
3419   HeapShared::initialize_from_archived_subgraph(THREAD, k);
3420 JVM_END
3421 
3422 JVM_ENTRY_PROF(void, JVM_RegisterLambdaProxyClassForArchiving, JVM_RegisterLambdaProxyClassForArchiving(JNIEnv* env,
3423                                               jclass caller,
3424                                               jstring interfaceMethodName,
3425                                               jobject factoryType,
3426                                               jobject interfaceMethodType,
3427                                               jobject implementationMember,
3428                                               jobject dynamicMethodType,
3429                                               jclass lambdaProxyClass))
3430 #if INCLUDE_CDS
3431   if (!CDSConfig::is_dumping_archive()) {
3432     return;
3433   }
3434 
3435   Klass* caller_k = java_lang_Class::as_Klass(JNIHandles::resolve(caller));
3436   InstanceKlass* caller_ik = InstanceKlass::cast(caller_k);
3437   if (caller_ik->is_hidden()) {
3438     // Hidden classes not of type lambda proxy classes are currently not being archived.
3439     // If the caller_ik is of one of the above types, the corresponding lambda proxy class won't be
3440     // registered for archiving.
3441     return;
3442   }
3443   Klass* lambda_k = java_lang_Class::as_Klass(JNIHandles::resolve(lambdaProxyClass));
3444   InstanceKlass* lambda_ik = InstanceKlass::cast(lambda_k);
3445   assert(lambda_ik->is_hidden(), "must be a hidden class");
3446   assert(!lambda_ik->is_non_strong_hidden(), "expected a strong hidden class");
3447 
3448   Symbol* interface_method_name = nullptr;
3449   if (interfaceMethodName != nullptr) {
3450     interface_method_name = java_lang_String::as_symbol(JNIHandles::resolve_non_null(interfaceMethodName));
3451   }
3452   Handle factory_type_oop(THREAD, JNIHandles::resolve_non_null(factoryType));
3453   Symbol* factory_type = java_lang_invoke_MethodType::as_signature(factory_type_oop(), true);
3454 
3455   Handle interface_method_type_oop(THREAD, JNIHandles::resolve_non_null(interfaceMethodType));
3456   Symbol* interface_method_type = java_lang_invoke_MethodType::as_signature(interface_method_type_oop(), true);
3457 
3458   Handle implementation_member_oop(THREAD, JNIHandles::resolve_non_null(implementationMember));
3459   assert(java_lang_invoke_MemberName::is_method(implementation_member_oop()), "must be");
3460   Method* m = java_lang_invoke_MemberName::vmtarget(implementation_member_oop());
3461 
3462   Handle dynamic_method_type_oop(THREAD, JNIHandles::resolve_non_null(dynamicMethodType));
3463   Symbol* dynamic_method_type = java_lang_invoke_MethodType::as_signature(dynamic_method_type_oop(), true);
3464 
3465   SystemDictionaryShared::add_lambda_proxy_class(caller_ik, lambda_ik, interface_method_name, factory_type,
3466                                                  interface_method_type, m, dynamic_method_type, THREAD);
3467 #endif // INCLUDE_CDS
3468 JVM_END
3469 
3470 JVM_ENTRY_PROF(jclass, JVM_LookupLambdaProxyClassFromArchive, JVM_LookupLambdaProxyClassFromArchive(JNIEnv* env,
3471                                                         jclass caller,
3472                                                         jstring interfaceMethodName,
3473                                                         jobject factoryType,
3474                                                         jobject interfaceMethodType,
3475                                                         jobject implementationMember,
3476                                                         jobject dynamicMethodType))
3477 #if INCLUDE_CDS
3478 
3479   if (interfaceMethodName == nullptr || factoryType == nullptr || interfaceMethodType == nullptr ||
3480       implementationMember == nullptr || dynamicMethodType == nullptr) {
3481     THROW_(vmSymbols::java_lang_NullPointerException(), nullptr);
3482   }
3483 
3484   Klass* caller_k = java_lang_Class::as_Klass(JNIHandles::resolve(caller));
3485   InstanceKlass* caller_ik = InstanceKlass::cast(caller_k);
3486   if (!caller_ik->is_shared()) {
3487     // there won't be a shared lambda class if the caller_ik is not in the shared archive.
3488     return nullptr;
3489   }
3490 
3491   Symbol* interface_method_name = java_lang_String::as_symbol(JNIHandles::resolve_non_null(interfaceMethodName));
3492   Handle factory_type_oop(THREAD, JNIHandles::resolve_non_null(factoryType));
3493   Symbol* factory_type = java_lang_invoke_MethodType::as_signature(factory_type_oop(), true);
3494 
3495   Handle interface_method_type_oop(THREAD, JNIHandles::resolve_non_null(interfaceMethodType));
3496   Symbol* interface_method_type = java_lang_invoke_MethodType::as_signature(interface_method_type_oop(), true);
3497 
3498   Handle implementation_member_oop(THREAD, JNIHandles::resolve_non_null(implementationMember));
3499   assert(java_lang_invoke_MemberName::is_method(implementation_member_oop()), "must be");
3500   Method* m = java_lang_invoke_MemberName::vmtarget(implementation_member_oop());
3501 
3502   Handle dynamic_method_type_oop(THREAD, JNIHandles::resolve_non_null(dynamicMethodType));
3503   Symbol* dynamic_method_type = java_lang_invoke_MethodType::as_signature(dynamic_method_type_oop(), true);
3504 
3505   InstanceKlass* lambda_ik = SystemDictionaryShared::get_shared_lambda_proxy_class(caller_ik, interface_method_name, factory_type,
3506                                                                                    interface_method_type, m, dynamic_method_type);
3507   jclass jcls = nullptr;
3508   if (lambda_ik != nullptr) {
3509     InstanceKlass* loaded_lambda = SystemDictionaryShared::prepare_shared_lambda_proxy_class(lambda_ik, caller_ik, THREAD);
3510     jcls = loaded_lambda == nullptr ? nullptr : (jclass) JNIHandles::make_local(THREAD, loaded_lambda->java_mirror());
3511   }
3512   return jcls;
3513 #else
3514   return nullptr;
3515 #endif // INCLUDE_CDS
3516 JVM_END
3517 
3518 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_GetRandomSeedForDumping, JVM_GetRandomSeedForDumping())
3519   if (CDSConfig::is_dumping_static_archive()) {
3520     // We do this so that the default CDS archive can be deterministic.
3521     const char* release = VM_Version::vm_release();
3522     const char* dbg_level = VM_Version::jdk_debug_level();
3523     const char* version = VM_Version::internal_vm_info_string();
3524     jlong seed = (jlong)(java_lang_String::hash_code((const jbyte*)release, (int)strlen(release)) ^
3525                          java_lang_String::hash_code((const jbyte*)dbg_level, (int)strlen(dbg_level)) ^
3526                          java_lang_String::hash_code((const jbyte*)version, (int)strlen(version)));
3527     seed += (jlong)VM_Version::vm_major_version();
3528     seed += (jlong)VM_Version::vm_minor_version();
3529     seed += (jlong)VM_Version::vm_security_version();
3530     seed += (jlong)VM_Version::vm_patch_version();
3531     if (seed == 0) { // don't let this ever be zero.
3532       seed = 0x87654321;
3533     }
3534     log_debug(cds)("JVM_GetRandomSeedForDumping() = " JLONG_FORMAT, seed);
3535     return seed;
3536   } else {
3537     return 0;
3538   }
3539 JVM_END
3540 
3541 JVM_ENTRY_NO_ENV_PROF(jint, JVM_GetCDSConfigStatus, JVM_GetCDSConfigStatus())
3542   return CDSConfig::get_status();
3543 JVM_END
3544 
3545 JVM_ENTRY_PROF(void, JVM_LogLambdaFormInvoker, JVM_LogLambdaFormInvoker(JNIEnv *env, jstring line))
3546 #if INCLUDE_CDS
3547   assert(CDSConfig::is_logging_lambda_form_invokers(), "sanity");
3548   if (line != nullptr) {
3549     ResourceMark rm(THREAD);
3550     Handle h_line (THREAD, JNIHandles::resolve_non_null(line));
3551     char* c_line = java_lang_String::as_utf8_string(h_line());
3552     if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) {
3553       // Note: LambdaFormInvokers::append take same format which is not
3554       // same as below the print format. The line does not include LAMBDA_FORM_TAG.
3555       LambdaFormInvokers::append(os::strdup((const char*)c_line, mtInternal));
3556     }
3557     if (ClassListWriter::is_enabled()) {
3558       ClassListWriter w;
3559       w.stream()->print_cr("%s %s", ClassListParser::lambda_form_tag(), c_line);
3560     }
3561   }
3562 #endif // INCLUDE_CDS
3563 JVM_END
3564 
3565 JVM_ENTRY_PROF(void, JVM_LogDynamicProxy, JVM_LogDynamicProxy(JNIEnv *env, jobject loader, jstring proxy_name, jobjectArray interfaces, jint access_flags))
3566 #if INCLUDE_CDS
3567   assert(CDSConfig::is_logging_dynamic_proxies(),  "sanity");
3568 
3569   ResourceMark rm(THREAD);
3570   oop proxy_name_oop = JNIHandles::resolve_non_null(proxy_name);
3571   char* proxy_name_str = java_lang_String::as_utf8_string(proxy_name_oop);
3572   oop loader_oop = JNIHandles::resolve(loader);
3573   objArrayOop interfaces_oop = objArrayOop(JNIHandles::resolve_non_null(interfaces));
3574 
3575   AOTConstantPoolResolver::trace_dynamic_proxy_class(loader_oop, proxy_name_str, interfaces_oop, access_flags);
3576 #endif // INCLUDE_CDS
3577 JVM_END
3578 
3579 JVM_ENTRY_PROF(void, JVM_DumpClassListToFile, JVM_DumpClassListToFile(JNIEnv *env, jstring listFileName))
3580 #if INCLUDE_CDS
3581   ResourceMark rm(THREAD);
3582   Handle file_handle(THREAD, JNIHandles::resolve_non_null(listFileName));
3583   char* file_name  = java_lang_String::as_utf8_string(file_handle());
3584   MetaspaceShared::dump_loaded_classes(file_name, THREAD);
3585 #endif // INCLUDE_CDS
3586 JVM_END
3587 
3588 JVM_ENTRY_PROF(void, JVM_DumpDynamicArchive, JVM_DumpDynamicArchive(JNIEnv *env, jstring archiveName))
3589 #if INCLUDE_CDS
3590   ResourceMark rm(THREAD);
3591   Handle file_handle(THREAD, JNIHandles::resolve_non_null(archiveName));
3592   char* archive_name  = java_lang_String::as_utf8_string(file_handle());
3593   DynamicArchive::dump_for_jcmd(archive_name, CHECK);
3594 #endif // INCLUDE_CDS
3595 JVM_END
3596 
3597 // Returns an array of all live Thread objects (VM internal JavaThreads,
3598 // jvmti agent threads, and JNI attaching threads  are skipped)
3599 // See CR 6404306 regarding JNI attaching threads
3600 JVM_ENTRY_PROF(jobjectArray, JVM_GetAllThreads, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3601   ResourceMark rm(THREAD);
3602   ThreadsListEnumerator tle(THREAD, false, false);
3603   JvmtiVMObjectAllocEventCollector oam;
3604 
3605   int num_threads = tle.num_threads();
3606   objArrayOop r = oopFactory::new_objArray(vmClasses::Thread_klass(), num_threads, CHECK_NULL);
3607   objArrayHandle threads_ah(THREAD, r);
3608 
3609   for (int i = 0; i < num_threads; i++) {
3610     Handle h = tle.get_threadObj(i);
3611     threads_ah->obj_at_put(i, h());
3612   }
3613 
3614   return (jobjectArray) JNIHandles::make_local(THREAD, threads_ah());
3615 JVM_END
3616 
3617 
3618 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3619 // Return StackTraceElement[][], each element is the stack trace of a thread in
3620 // the corresponding entry in the given threads array
3621 JVM_ENTRY_PROF(jobjectArray, JVM_DumpThreads, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3622   JvmtiVMObjectAllocEventCollector oam;
3623 
3624   // Check if threads is null
3625   if (threads == nullptr) {
3626     THROW_NULL(vmSymbols::java_lang_NullPointerException());
3627   }
3628 
3629   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3630   objArrayHandle ah(THREAD, a);
3631   int num_threads = ah->length();
3632   // check if threads is non-empty array
3633   if (num_threads == 0) {
3634     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
3635   }
3636 
3637   // check if threads is not an array of objects of Thread class
3638   Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3639   if (k != vmClasses::Thread_klass()) {
3640     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
3641   }
3642 
3643   ResourceMark rm(THREAD);
3644 
3645   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3646   for (int i = 0; i < num_threads; i++) {
3647     oop thread_obj = ah->obj_at(i);
3648     instanceHandle h(THREAD, (instanceOop) thread_obj);
3649     thread_handle_array->append(h);
3650   }
3651 
3652   // The JavaThread references in thread_handle_array are validated
3653   // in VM_ThreadDump::doit().
3654   Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3655   return (jobjectArray)JNIHandles::make_local(THREAD, stacktraces());
3656 
3657 JVM_END
3658 
3659 // JVM monitoring and management support
3660 JVM_LEAF_PROF(void*, JVM_GetManagement, JVM_GetManagement(jint version))
3661   return Management::get_jmm_interface(version);
3662 JVM_END
3663 
3664 // com.sun.tools.attach.VirtualMachine agent properties support
3665 //
3666 // Initialize the agent properties with the properties maintained in the VM
3667 JVM_ENTRY_PROF(jobject, JVM_InitAgentProperties, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3668   ResourceMark rm;
3669 
3670   Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3671 
3672   PUTPROP(props, "sun.java.command", Arguments::java_command());
3673   PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3674   PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3675   return properties;
3676 JVM_END
3677 
3678 JVM_ENTRY_PROF(jobjectArray, JVM_GetEnclosingMethodInfo, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3679 {
3680   JvmtiVMObjectAllocEventCollector oam;
3681 
3682   if (ofClass == nullptr) {
3683     return nullptr;
3684   }
3685   Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3686   // Special handling for primitive objects
3687   if (java_lang_Class::is_primitive(mirror())) {
3688     return nullptr;
3689   }
3690   Klass* k = java_lang_Class::as_Klass(mirror());
3691   if (!k->is_instance_klass()) {
3692     return nullptr;
3693   }
3694   InstanceKlass* ik = InstanceKlass::cast(k);
3695   int encl_method_class_idx = ik->enclosing_method_class_index();
3696   if (encl_method_class_idx == 0) {
3697     return nullptr;
3698   }
3699   objArrayOop dest_o = oopFactory::new_objArray(vmClasses::Object_klass(), 3, CHECK_NULL);
3700   objArrayHandle dest(THREAD, dest_o);
3701   Klass* enc_k = ik->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3702   dest->obj_at_put(0, enc_k->java_mirror());
3703   int encl_method_method_idx = ik->enclosing_method_method_index();
3704   if (encl_method_method_idx != 0) {
3705     Symbol* sym = ik->constants()->symbol_at(
3706                         extract_low_short_from_int(
3707                           ik->constants()->name_and_type_at(encl_method_method_idx)));
3708     Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3709     dest->obj_at_put(1, str());
3710     sym = ik->constants()->symbol_at(
3711               extract_high_short_from_int(
3712                 ik->constants()->name_and_type_at(encl_method_method_idx)));
3713     str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3714     dest->obj_at_put(2, str());
3715   }
3716   return (jobjectArray) JNIHandles::make_local(THREAD, dest());
3717 }
3718 JVM_END
3719 
3720 // Returns an array of java.lang.String objects containing the input arguments to the VM.
3721 JVM_ENTRY_PROF(jobjectArray, JVM_GetVmArguments, JVM_GetVmArguments(JNIEnv *env))
3722   ResourceMark rm(THREAD);
3723 
3724   if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
3725     return nullptr;
3726   }
3727 
3728   char** vm_flags = Arguments::jvm_flags_array();
3729   char** vm_args = Arguments::jvm_args_array();
3730   int num_flags = Arguments::num_jvm_flags();
3731   int num_args = Arguments::num_jvm_args();
3732 
3733   InstanceKlass* ik = vmClasses::String_klass();
3734   objArrayOop r = oopFactory::new_objArray(ik, num_args + num_flags, CHECK_NULL);
3735   objArrayHandle result_h(THREAD, r);
3736 
3737   int index = 0;
3738   for (int j = 0; j < num_flags; j++, index++) {
3739     Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
3740     result_h->obj_at_put(index, h());
3741   }
3742   for (int i = 0; i < num_args; i++, index++) {
3743     Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
3744     result_h->obj_at_put(index, h());
3745   }
3746   return (jobjectArray) JNIHandles::make_local(THREAD, result_h());
3747 JVM_END
3748 
3749 JVM_LEAF_PROF(jint, JVM_FindSignal, JVM_FindSignal(const char *name))
3750   return os::get_signal_number(name);
3751 JVM_END
3752 
3753 JVM_ENTRY_PROF(void, JVM_VirtualThreadStart, JVM_VirtualThreadStart(JNIEnv* env, jobject vthread))
3754 #if INCLUDE_JVMTI
3755   if (!DoJVMTIVirtualThreadTransitions) {
3756     assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3757     return;
3758   }
3759   if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3760     JvmtiVTMSTransitionDisabler::VTMS_vthread_start(vthread);
3761   } else {
3762     // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3763     JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, false);
3764   }
3765 #endif
3766 JVM_END
3767 
3768 JVM_ENTRY_PROF(void, JVM_VirtualThreadEnd, JVM_VirtualThreadEnd(JNIEnv* env, jobject vthread))
3769 #if INCLUDE_JVMTI
3770   if (!DoJVMTIVirtualThreadTransitions) {
3771     assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3772     return;
3773   }
3774   if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3775     JvmtiVTMSTransitionDisabler::VTMS_vthread_end(vthread);
3776   } else {
3777     // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3778     JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, true);
3779   }
3780 #endif
3781 JVM_END
3782 
3783 // If notifications are disabled then just update the VTMS transition bit and return.
3784 // Otherwise, the bit is updated in the given jvmtiVTMSTransitionDisabler function call.
3785 JVM_ENTRY_PROF(void, JVM_VirtualThreadMount, JVM_VirtualThreadMount(JNIEnv* env, jobject vthread, jboolean hide))
3786 #if INCLUDE_JVMTI
3787   if (!DoJVMTIVirtualThreadTransitions) {
3788     assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3789     return;
3790   }
3791   if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3792     JvmtiVTMSTransitionDisabler::VTMS_vthread_mount(vthread, hide);
3793   } else {
3794     // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3795     JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, hide);
3796   }
3797 #endif
3798 JVM_END
3799 
3800 // If notifications are disabled then just update the VTMS transition bit and return.
3801 // Otherwise, the bit is updated in the given jvmtiVTMSTransitionDisabler function call below.
3802 JVM_ENTRY_PROF(void, JVM_VirtualThreadUnmount, JVM_VirtualThreadUnmount(JNIEnv* env, jobject vthread, jboolean hide))
3803 #if INCLUDE_JVMTI
3804   if (!DoJVMTIVirtualThreadTransitions) {
3805     assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3806     return;
3807   }
3808   if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3809     JvmtiVTMSTransitionDisabler::VTMS_vthread_unmount(vthread, hide);
3810   } else {
3811     // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3812     JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, hide);
3813   }
3814 #endif
3815 JVM_END
3816 
3817 // Notification from VirtualThread about disabling JVMTI Suspend in a sync critical section.
3818 // Needed to avoid deadlocks with JVMTI suspend mechanism.
3819 JVM_ENTRY(void, JVM_VirtualThreadDisableSuspend(JNIEnv* env, jclass clazz, jboolean enter))
3820 #if INCLUDE_JVMTI
3821   if (!DoJVMTIVirtualThreadTransitions) {
3822     assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3823     return;
3824   }
3825   assert(thread->is_disable_suspend() != (bool)enter,
3826          "nested or unbalanced monitor enter/exit is not allowed");
3827   thread->toggle_is_disable_suspend();
3828 #endif
3829 JVM_END
3830 
3831 JVM_ENTRY(void, JVM_VirtualThreadPinnedEvent(JNIEnv* env, jclass ignored, jstring op))
3832 #if INCLUDE_JFR
3833   freeze_result result = THREAD->last_freeze_fail_result();
3834   assert(result != freeze_ok, "sanity check");
3835   EventVirtualThreadPinned event(UNTIMED);
3836   event.set_starttime(THREAD->last_freeze_fail_time());
3837   if (event.should_commit()) {
3838     ResourceMark rm(THREAD);
3839     const char *str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(op));
3840     THREAD->post_vthread_pinned_event(&event, str, result);
3841   }
3842 #endif
3843 JVM_END
3844 
3845 JVM_ENTRY(jobject, JVM_TakeVirtualThreadListToUnblock(JNIEnv* env, jclass ignored))
3846   ParkEvent* parkEvent = ObjectMonitor::vthread_unparker_ParkEvent();
3847   assert(parkEvent != nullptr, "not initialized");
3848 
3849   OopHandle& list_head = ObjectMonitor::vthread_cxq_head();
3850   oop vthread_head = nullptr;
3851   while (true) {
3852     if (list_head.peek() != nullptr) {
3853       for (;;) {
3854         oop head = list_head.resolve();
3855         if (list_head.cmpxchg(head, nullptr) == head) {
3856           return JNIHandles::make_local(THREAD, head);
3857         }
3858       }
3859     }
3860     ThreadBlockInVM tbivm(THREAD);
3861     parkEvent->park();
3862   }
3863 JVM_END
3864 /*
3865  * Return the current class's class file version.  The low order 16 bits of the
3866  * returned jint contain the class's major version.  The high order 16 bits
3867  * contain the class's minor version.
3868  */
3869 JVM_ENTRY_PROF(jint, JVM_GetClassFileVersion, JVM_GetClassFileVersion(JNIEnv* env, jclass current))
3870   oop mirror = JNIHandles::resolve_non_null(current);
3871   if (java_lang_Class::is_primitive(mirror)) {
3872     // return latest major version and minor version of 0.
3873     return JVM_CLASSFILE_MAJOR_VERSION;
3874   }
3875   assert(!java_lang_Class::as_Klass(mirror)->is_array_klass(), "unexpected array class");
3876 
3877   Klass* c = java_lang_Class::as_Klass(mirror);
3878   assert(c->is_instance_klass(), "must be");
3879   InstanceKlass* ik = InstanceKlass::cast(c);
3880   return (ik->minor_version() << 16) | ik->major_version();
3881 JVM_END
3882 
3883 /*
3884  * Ensure that code doing a stackwalk and using javaVFrame::locals() to
3885  * get the value will see a materialized value and not a scalar-replaced
3886  * null value.
3887  */
3888 JVM_ENTRY_PROF(void, JVM_EnsureMaterializedForStackWalk_func, JVM_EnsureMaterializedForStackWalk_func(JNIEnv* env, jobject vthread, jobject value))
3889   JVM_EnsureMaterializedForStackWalk(env, value);
3890 JVM_END
3891 
3892 /*
3893  * Return JNI_TRUE if warnings are printed when agents are dynamically loaded.
3894  */
3895 JVM_LEAF_PROF(jboolean, JVM_PrintWarningAtDynamicAgentLoad, JVM_PrintWarningAtDynamicAgentLoad(void))
3896   return (EnableDynamicAgentLoading && !FLAG_IS_CMDLINE(EnableDynamicAgentLoading)) ? JNI_TRUE : JNI_FALSE;
3897 JVM_END
3898 
3899 #define DO_COUNTERS(macro) \
3900   macro(JVM_CurrentTimeMillis) \
3901   macro(JVM_NanoTime) \
3902   macro(JVM_GetNanoTimeAdjustment) \
3903   macro(JVM_ArrayCopy) \
3904   macro(JVM_GetProperties) \
3905   macro(JVM_GetTemporaryDirectory) \
3906   macro(JVM_BeforeHalt) \
3907   macro(JVM_Halt) \
3908   macro(JVM_GC) \
3909   macro(JVM_MaxObjectInspectionAge) \
3910   macro(JVM_TotalMemory) \
3911   macro(JVM_FreeMemory) \
3912   macro(JVM_MaxMemory) \
3913   macro(JVM_ActiveProcessorCount) \
3914   macro(JVM_IsUseContainerSupport) \
3915   macro(JVM_FillInStackTrace) \
3916   macro(JVM_GetExtendedNPEMessage) \
3917   macro(JVM_InitStackTraceElementArray) \
3918   macro(JVM_InitStackTraceElement) \
3919   macro(JVM_ExpandStackFrameInfo) \
3920   macro(JVM_CallStackWalk) \
3921   macro(JVM_MoreStackWalk) \
3922   macro(JVM_SetStackWalkContinuation) \
3923   macro(JVM_IHashCode) \
3924   macro(JVM_MonitorWait) \
3925   macro(JVM_MonitorNotify) \
3926   macro(JVM_MonitorNotifyAll) \
3927   macro(JVM_Clone) \
3928   macro(JVM_ReportFinalizationComplete) \
3929   macro(JVM_IsFinalizationEnabled) \
3930   macro(JVM_RegisterContinuationMethods) \
3931   macro(JVM_NativePath) \
3932   macro(JVM_GetCallerClass) \
3933   macro(JVM_FindPrimitiveClass) \
3934   macro(JVM_FindClassFromBootLoader) \
3935   macro(JVM_FindClassFromCaller) \
3936   macro(JVM_FindClassFromClass) \
3937   macro(JVM_DefineClass) \
3938   macro(JVM_LookupDefineClass) \
3939   macro(JVM_DefineClassWithSource) \
3940   macro(JVM_FindLoadedClass) \
3941   macro(JVM_DefineModule) \
3942   macro(JVM_SetBootLoaderUnnamedModule) \
3943   macro(JVM_AddModuleExports) \
3944   macro(JVM_AddModuleExportsToAllUnnamed) \
3945   macro(JVM_AddModuleExportsToAll) \
3946   macro(JVM_AddReadsModule) \
3947   macro(JVM_DefineArchivedModules) \
3948   macro(JVM_InitClassName) \
3949   macro(JVM_GetClassInterfaces) \
3950   macro(JVM_IsInterface) \
3951   macro(JVM_IsHiddenClass) \
3952   macro(JVM_GetProtectionDomain) \
3953   macro(JVM_FindScopedValueBindings) \
3954   macro(JVM_IsArrayClass) \
3955   macro(JVM_IsPrimitiveClass) \
3956   macro(JVM_GetClassModifiers) \
3957   macro(JVM_GetDeclaredClasses) \
3958   macro(JVM_GetDeclaringClass) \
3959   macro(JVM_GetSimpleBinaryName) \
3960   macro(JVM_GetClassSignature) \
3961   macro(JVM_GetClassAnnotations) \
3962   macro(JVM_GetClassTypeAnnotations) \
3963   macro(JVM_GetMethodTypeAnnotations) \
3964   macro(JVM_GetFieldTypeAnnotations) \
3965   macro(JVM_GetMethodParameters) \
3966   macro(JVM_GetClassDeclaredFields) \
3967   macro(JVM_IsRecord) \
3968   macro(JVM_GetRecordComponents) \
3969   macro(JVM_GetClassDeclaredMethods) \
3970   macro(JVM_GetClassDeclaredConstructors) \
3971   macro(JVM_GetClassAccessFlags) \
3972   macro(JVM_AreNestMates) \
3973   macro(JVM_GetNestHost) \
3974   macro(JVM_GetNestMembers) \
3975   macro(JVM_GetPermittedSubclasses) \
3976   macro(JVM_GetClassConstantPool) \
3977   macro(JVM_ConstantPoolGetSize) \
3978   macro(JVM_ConstantPoolGetClassAt) \
3979   macro(JVM_ConstantPoolGetClassAtIfLoaded) \
3980   macro(JVM_ConstantPoolGetMethodAt) \
3981   macro(JVM_ConstantPoolGetMethodAtIfLoaded) \
3982   macro(JVM_ConstantPoolGetFieldAt) \
3983   macro(JVM_ConstantPoolGetFieldAtIfLoaded) \
3984   macro(JVM_ConstantPoolGetMemberRefInfoAt) \
3985   macro(JVM_ConstantPoolGetClassRefIndexAt) \
3986   macro(JVM_ConstantPoolGetNameAndTypeRefIndexAt) \
3987   macro(JVM_ConstantPoolGetNameAndTypeRefInfoAt) \
3988   macro(JVM_ConstantPoolGetIntAt) \
3989   macro(JVM_ConstantPoolGetLongAt) \
3990   macro(JVM_ConstantPoolGetFloatAt) \
3991   macro(JVM_ConstantPoolGetDoubleAt) \
3992   macro(JVM_ConstantPoolGetStringAt) \
3993   macro(JVM_ConstantPoolGetUTF8At) \
3994   macro(JVM_ConstantPoolGetTagAt) \
3995   macro(JVM_DesiredAssertionStatus) \
3996   macro(JVM_AssertionStatusDirectives) \
3997   macro(JVM_GetClassNameUTF) \
3998   macro(JVM_GetClassCPTypes) \
3999   macro(JVM_GetClassCPEntriesCount) \
4000   macro(JVM_GetClassFieldsCount) \
4001   macro(JVM_GetClassMethodsCount) \
4002   macro(JVM_GetMethodIxExceptionIndexes) \
4003   macro(JVM_GetMethodIxExceptionsCount) \
4004   macro(JVM_GetMethodIxByteCode) \
4005   macro(JVM_GetMethodIxByteCodeLength) \
4006   macro(JVM_GetMethodIxExceptionTableEntry) \
4007   macro(JVM_GetMethodIxExceptionTableLength) \
4008   macro(JVM_GetMethodIxModifiers) \
4009   macro(JVM_GetFieldIxModifiers) \
4010   macro(JVM_GetMethodIxLocalsCount) \
4011   macro(JVM_GetMethodIxArgsSize) \
4012   macro(JVM_GetMethodIxMaxStack) \
4013   macro(JVM_IsConstructorIx) \
4014   macro(JVM_IsVMGeneratedMethodIx) \
4015   macro(JVM_GetMethodIxNameUTF) \
4016   macro(JVM_GetMethodIxSignatureUTF) \
4017   macro(JVM_GetCPFieldNameUTF) \
4018   macro(JVM_GetCPMethodNameUTF) \
4019   macro(JVM_GetCPMethodSignatureUTF) \
4020   macro(JVM_GetCPFieldSignatureUTF) \
4021   macro(JVM_GetCPClassNameUTF) \
4022   macro(JVM_GetCPFieldClassNameUTF) \
4023   macro(JVM_GetCPMethodClassNameUTF) \
4024   macro(JVM_GetCPFieldModifiers) \
4025   macro(JVM_GetCPMethodModifiers) \
4026   macro(JVM_ReleaseUTF) \
4027   macro(JVM_IsSameClassPackage) \
4028   macro(JVM_StartThread) \
4029   macro(JVM_SetThreadPriority) \
4030   macro(JVM_Yield) \
4031   macro(JVM_SleepNanos) \
4032   macro(JVM_CurrentCarrierThread) \
4033   macro(JVM_CurrentThread) \
4034   macro(JVM_SetCurrentThread) \
4035   macro(JVM_GetNextThreadIdOffset) \
4036   macro(JVM_Interrupt) \
4037   macro(JVM_HoldsLock) \
4038   macro(JVM_GetStackTrace) \
4039   macro(JVM_SetNativeThreadName) \
4040   macro(JVM_ScopedValueCache) \
4041   macro(JVM_SetScopedValueCache) \
4042   macro(JVM_GetSystemPackage) \
4043   macro(JVM_GetSystemPackages) \
4044   macro(JVM_GetAndClearReferencePendingList) \
4045   macro(JVM_HasReferencePendingList) \
4046   macro(JVM_WaitForReferencePendingList) \
4047   macro(JVM_ReferenceRefersTo) \
4048   macro(JVM_ReferenceClear) \
4049   macro(JVM_PhantomReferenceRefersTo) \
4050   macro(JVM_LatestUserDefinedLoader) \
4051   macro(JVM_GetArrayLength) \
4052   macro(JVM_GetArrayElement) \
4053   macro(JVM_GetPrimitiveArrayElement) \
4054   macro(JVM_SetArrayElement) \
4055   macro(JVM_SetPrimitiveArrayElement) \
4056   macro(JVM_NewArray) \
4057   macro(JVM_NewMultiArray) \
4058   macro(JVM_LoadZipLibrary) \
4059   macro(JVM_LoadLibrary) \
4060   macro(JVM_UnloadLibrary) \
4061   macro(JVM_FindLibraryEntry) \
4062   macro(JVM_IsSupportedJNIVersion) \
4063   macro(JVM_IsPreviewEnabled) \
4064   macro(JVM_IsContinuationsSupported) \
4065   macro(JVM_IsForeignLinkerSupported) \
4066   macro(JVM_InternString) \
4067   macro(JVM_InvokeMethod) \
4068   macro(JVM_NewInstanceFromConstructor) \
4069   macro(JVM_InitializeFromArchive) \
4070   macro(JVM_RegisterLambdaProxyClassForArchiving) \
4071   macro(JVM_LookupLambdaProxyClassFromArchive) \
4072   macro(JVM_GetRandomSeedForDumping) \
4073   macro(JVM_LogLambdaFormInvoker) \
4074   macro(JVM_LogDynamicProxy) \
4075   macro(JVM_DumpClassListToFile) \
4076   macro(JVM_DumpDynamicArchive) \
4077   macro(JVM_GetAllThreads) \
4078   macro(JVM_DumpThreads) \
4079   macro(JVM_GetManagement) \
4080   macro(JVM_InitAgentProperties) \
4081   macro(JVM_GetEnclosingMethodInfo) \
4082   macro(JVM_GetVmArguments) \
4083   macro(JVM_FindSignal) \
4084   macro(JVM_VirtualThreadStart) \
4085   macro(JVM_VirtualThreadEnd) \
4086   macro(JVM_VirtualThreadMount) \
4087   macro(JVM_VirtualThreadUnmount) \
4088   macro(JVM_GetClassFileVersion) \
4089   macro(JVM_EnsureMaterializedForStackWalk_func) \
4090   macro(JVM_PrintWarningAtDynamicAgentLoad)
4091 
4092 #define INIT_COUNTER(name) \
4093     NEWPERFTICKCOUNTERS(_perf_##name##_timer, SUN_RT, #name); \
4094     NEWPERFEVENTCOUNTER(_perf_##name##_count, SUN_RT, #name "_count"); \
4095 
4096 void perf_jvm_init() {
4097   if (ProfileVMCalls && UsePerfData) {
4098     EXCEPTION_MARK;
4099 
4100     DO_COUNTERS(INIT_COUNTER)
4101 
4102     if (HAS_PENDING_EXCEPTION) {
4103       vm_exit_during_initialization("jvm_perf_init failed unexpectedly");
4104     }
4105   }
4106 }
4107 
4108 #undef INIT_COUNTER
4109 
4110 #define PRINT_COUNTER(name) {\
4111   jlong count = _perf_##name##_count->get_value(); \
4112   if (count > 0) { \
4113     st->print_cr("  %-40s = " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) "us (thread) (" JLONG_FORMAT_W(5) " events)", \
4114                  #name,                                                   \
4115                  _perf_##name##_timer->elapsed_counter_value_us(),        \
4116                  _perf_##name##_timer->thread_counter_value_us(), count); \
4117   }}
4118 
4119 void perf_jvm_print_on(outputStream* st) {
4120   if (ProfileVMCalls && UsePerfData) {
4121     DO_COUNTERS(PRINT_COUNTER)
4122   } else {
4123     st->print_cr("  JVM:  no info (%s is disabled)", (UsePerfData ? "ProfileVMCalls" : "UsePerfData"));
4124   }
4125 }
4126 
4127 #undef PRINT_COUNTER