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