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