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