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