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