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