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