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