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