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