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