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