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