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