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