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