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