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