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