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