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