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