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