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