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